Leetcode030 substring-with-concatenation-of-all-words 字符串查找
题目描述
给出一个字符串S和一组单词L,L中单词的长度都相等,找出S中的符合以下要求的子串在S中的起始位置索引:子串为L中所有单词串联在一起(单词的顺序随意),L中的每个单词只出现一次,中间不能有其他的字符。
例如:给定S="barfoothefoobarman",L为["foo", "bar"],
返回的索引应该是[0,9].(不用关心给出索引的顺序)
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).
思路:L中字符串长度相同,找出S中L所有单词组合,且数目一致的位置。
所以遍历时,i+length*L.size()<=S.size(),然后切割每个length的单词去查找,m1中存放L每个单词的出现次数,m2[tmp]<m1[tmp]时,才说明是对的,可以继续查找。当找到的tmp数==L.size()时,表明该位置是正确的。
class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; if(S.empty()||L.empty()) return res; map<string,int> m1,m2; for(int i=0;i<L.size();++i) { m1[L[i]] = m1[L[i]]==0?1:m1[L[i]]+1; } int length = L[0].size(); for(int i =0;i+length*L.size()<=S.size();++i) { m2.clear(); int j; for(j=0;j<L.size();++j) { string tmp = S.substr(i+j*length,length); if(m1[tmp]!=0&&m1[tmp]>m2[tmp]) { m2[tmp]=m2[tmp]==0?1:m2[tmp]+1; } else break; } if(j==L.size()) { res.push_back(i); } } return res; } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=