leetcodeのSubstring with Concatenation of All Words
Substring with Concatenation of All Words
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:
You should return the indices:
構想:テーマはL中のすべての単語を含む開始位置を見つけることを意味するが、多くも少なくもなく、ちょうどL中のすべての単語を含むようにしなければならない.そして、隣接する2つの開始位置は重なることもできる.例えば、S=「aaa」、L=['a','a']で、結果は[0,1]である.具体的な方法は最短要約と少し似ていて、need配列で必要なすべての単語を保存し、hasFindは見つかった単語を保存し、hasFindがneedより大きい場合、この位置は満たされず、2つの配列が完全に同じ場合にのみ満たされます.
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中のすべての単語を含む開始位置を見つけることを意味するが、多くも少なくもなく、ちょうどL中のすべての単語を含むようにしなければならない.そして、隣接する2つの開始位置は重なることもできる.例えば、S=「aaa」、L=['a','a']で、結果は[0,1]である.具体的な方法は最短要約と少し似ていて、need配列で必要なすべての単語を保存し、hasFindは見つかった単語を保存し、hasFindがneedより大きい場合、この位置は満たされず、2つの配列が完全に同じ場合にのみ満たされます.
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L)
{
int totalWord = L.size(),wordLen = L[0].size(),i,j;
map<string,int> needWord;
vector<int> res;
for (i = 0;i < totalWord;i++)needWord[L[i]]++;//
for(i = 0;i + totalWord*wordLen <= S.size();i++)
{
map<string,int> hasFindWord;
for (j =0;j < totalWord;j++)//
{
string sub = S.substr(i+j*wordLen,wordLen);//
map<string,int>::iterator iter = needWord.find(sub);
if(iter == needWord.end())break;
hasFindWord[sub]++;
if(hasFindWord[sub] > needWord[sub])break;
}
if(j == totalWord) res.push_back(i);
}
return res;
}
};