题目大意:在字符串s中找出包含“字符串数组words中的所有词”的子串开头下标,子串中除了words中的词之外不能有其他字符,words中的字符串长度都相同。
分析:字符串和map的考察。思路就是利用map储存words中的每个单词在words中的出现次数,然后循环从字符串s的每个下标开始找出子串,查询words中的单词是否存在于子串中,且无多余字符,如果满足要求则将本次循环索引下标加入答案即可。
代码:转载自https://blog.csdn.net/zhangxiao93/article/details/49007779
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> result;
if (s == "" || words.empty()) {
return result;
}
int sLen = s.size();//母串的总长度
int wordLen = words[0].size();//单个单词的长度
int wordCount = words.size();//单词的个数
int subLen = wordLen * wordCount;//每次需要从母串中拿来进行匹配的子串的长度
map<string, int> myWords; //储存每个单词在words中出现的次数
int i, j, k;
for (i = 0; i < wordCount; i++) {
myWords[words[i]]++;
}
i = 0;
while (i < sLen - subLen + 1) { //i是在s中找subLen的索引下标
map<string, int> tempMap(myWords);
int subCount = i + subLen;//本次从母串拿出来的下标为(i,subCount-1)
k = i;
//不能直接while(k<subLen + i)因为满足当i自增后会循环条件变化,内循环会多循环一次
while (k < subCount) {
string temp = s.substr(k, wordLen);//取出一个与word长度一样的子串
if (tempMap.find(temp) == tempMap.end()) {//没有找到说明从i开头的子串中没有需要的单词,这个直接时候i++,并跳出循环 //从s中取出的子串中不含words中的任何一个词
i++;
break;
}
else { //在本次取出的subLen长度的子串中找到了words中的某一个
if (tempMap[temp] > 0) { //取出的temp正好是words中的一个
tempMap[temp]--;//找到后从临时Map中剔除
k += wordLen;//k跳到下一个单词
if (k == subCount) { //当比对下标走到子串末尾时说明比对成功
result.push_back(i);
i++;
}
}
else {//取出的temp不是words中的词,也就是说有多余词在子串中出现
i++;
break;
}
}
}
}
return result;
}
};