棋子

导航

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 wordsexactly 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).

 

 

下面这段代码只能通过三分之二的测试用例,因为a concatenation of each word in wordsexactly once,我能说题目意思给的不明确么?

网上还有应用“滑动窗口”的时间复杂度为O(n)算法,后面再分析!

 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string s, vector<string>& words) {
 4         vector<int> res;
 5         int wordNum=words.size(),wordLen=words[0].size();
 6         if(s.size()<wordLen*wordNum)
 7             return res;
 8         map<string,int> dic,curWord;
 9         for(int i=0;i<wordNum;i++)
10         {
11             dic[words[i]]++;
12         }
13         for(int i=0;i<s.size()-wordLen*wordNum;i++)
14         {
15             curWord.clear();
16             int count=0;
17             for(int j=0;j<wordNum;j++)
18             {
19                 string word=s.substr(i+j*wordLen,wordLen);
20                 if(dic.find(word)==dic.end())
21                     break;
22                 curWord[word]++;
23                 count++;
24                 if(curWord[word]>dic[word])
25                     break;
26             }
27             if(count==wordNum)
28                 res.push_back(i);
29         }
30         return res;
31     }
32 };

 

posted on 2015-12-24 14:53  鼬与轮回  阅读(190)  评论(0编辑  收藏  举报