您的位置:首页 > 其它

[LeetCode]Substring with Concatenation of All Words

2013-11-26 21:16 459 查看
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:

S:
"barfoothefoobarman"


L:
["foo", "bar"]


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

(order does not matter).

思考:两个map。判断单词是否存在,出现次数是否相同。

class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> res;
map<string,int> words;
map<string,int> visited;
map<string,int>::iterator iter1,iter2;
int i,j;
int len=L[0].size();
if(S.size()<L.size()*len) return res;
for(i=0;i<L.size();i++) words[L[i]]++;
for(i=0;i<=S.size()-L.size()*len;i++)
{
visited.clear();
for(j=i;j<=S.size()-len;j=j+len)
{
string temp=S.substr(j,len);
iter1=words.find(temp);
iter2=visited.find(temp);
if(iter1==words.end()) break;
if(iter1->second<=iter2->second) break;
visited[temp]++;
}
if(words==visited) res.push_back(i);
}
return res;
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: