您的位置:首页 > 其它

Substring with Concatenation of All Words 字符串操作 匹配的字串数

2015-06-25 14:13 429 查看


Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that
is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:

s:
"barfoothefoobarman"


words:
["foo", "bar"]

You should return the indices:
[0,9]
.

(order does not matter).
class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        
       
        int wordLen=words.size();
        vector<int> res;
        
        if(wordLen<=0)
            return res;
    
        int wordSize=words[0].size();
        
        int i,j;
        map<string,int> wordCount;
        //map统计每个单词出现
        for(i=0;i<wordLen;i++)
            wordCount[words[i]]++;
        
        map<string,int> tmp;
        int len=s.length();
       // for(i=0;i<=s.length()-(wordLen*wordSize);i++) 刚开始s.length没有用int转换一直过不了
       //改为i<=(int)s.length() 过了
        for(i=0;i<=len-(wordLen*wordSize);i++)
        {
            tmp.clear();
            for(j=0;j<wordLen;j++)
            {
               string str=s.substr(i+j*wordSize,wordSize);
               if(wordCount.find(str)!=wordCount.end())
               {
                   tmp[str]++;
                   if(tmp[str]>wordCount[str])
                        break;
               }
               else
                    break;
            }
            if(j==wordLen)
                res.push_back(i);
        }
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: