标签:
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).
代码如下(这道题目题意理解有问题,只能通过约75%的测试用例):
一个未通过的测试用例如下(s中good可以多于‘词典’中的个数):
1 class Solution { 2 public: 3 vector<int> findSubstring(string s, vector<string>& words) 4 { 5 vector<int> res; 6 7 int wordLen=words[0].size(),wordNum=words.size(); 8 if(s.size()<wordLen*wordNum) 9 return res; 10 map<string,int> dic,curWord; 11 for(int i=0;i<wordNum;i++) 12 dic[words[i]]++; 13 for(int i=0;i<s.size()-wordLen*wordNum;i++) 14 { 15 curWord.clear(); 16 int j; 17 for(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 if(curWord[word]>dic[word]) 24 break; 25 } 26 if(j==wordNum) 27 res.push_back(i); 28 } 29 return res; 30 } 31 };
Substring with Concatenation of All Words
标签:
原文地址:http://www.cnblogs.com/chess/p/5140937.html