30、Substring with Concatenation of All Words
子字符串連接的單詞
現有一組長度相等的字符串words,要在原字符串中找出正好包含words中所有字符串的子字符串的起始位置。
例子:
輸入: s = “barfoothefoobarman”, words = [“foo”, “bar”]輸出: [0, 9]
分析:
1.這道題是尋找子字符串的深化版本,尋找的子字符串是由多個等長的字符串連接在一起的,難點就在於子字符串之間沒有先後順序。
2.就是我們需要確保每一個子字符串都只出現了一次,所以我們需要兩個unordered_map<string,int>來存儲字符串和他的出現次數,一個做爲對比模板,一個做爲查找計數。
3.迭代原字符串,每當找到一個同words中的字符串時,就進入循環類比接下來同樣長度的字符串中是否與words相同且不重複,達成則記錄迭代,否則break。
代碼:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
unordered_map<string,int> compare;//比較模板
for(string w:words)
compare[w]++;
int n=s.length(),num=words.size(),len=words[0].length();
vector<int> res;
for(int i=0;i<=n-num*len+1;i++)
{
unordered_map<string,int>counts;//計數
int j=0;
for(;j<num;j++)
{
string word=s.substr(i+j*len,len);//複製
if(compare.find(word)!=compare.end())
{
counts[word]++;
if(counts[word]>compare[word])
break;
}
else break;
}
if(j==num)res.push_back(i);
}
return res;
}
};