思路:读完题最直接的思路就是,建立一个set集合,把words数组里可能组成的所有字符组合均存放在这个集合里,然后遍历一遍字符串s,就可以了。但是这种思路难点就在于words包含的单词个数不定。常规没办法求出所有可能的组合,但是如果用上回溯感觉没准应该能做出来,但是目前没有什么思路,所以按照其他大佬的思路写了一遍这道题。
学习思路:详细通俗的思路分析,多解法 - 串联所有单词的子串 - 力扣(LeetCode)
具体代码:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
int wordNum = words.size();
int wordSize = words[0].size();
int wordLength = wordSize * wordNum;
if (words.size() == 0)
{
return res;
}
unordered_map<string, int> m1;
for (int i = 0; i < wordNum; i++)
{
m1[words[i]]++;
}
unordered_map<string, int> m2;
for (int i = 0; (i + wordLength) <= s.size(); i++)
{
int j = 0;
for (j = i ; j < (i + wordLength) ; j = j + wordSize)
{
string tmps = s.substr(j, wordSize);
if (m1[tmps] == 0)
{
break;
}
else
{
m2[tmps]++;
if (m1[tmps]<m2[tmps])
{
break;
}
}
}
if (j == (i + wordLength))
{
res.push_back(i);
}
m2.clear();
}
return res;
}