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:
L:
S:
"barfoothefoobarman"L:
["foo", "bar"]
You should return the indices:
(order does not matter).
[0,9].(order does not matter).
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> res;
if (L.size()<=0)
return res;
int wordCount = L.size();
int wordSize = L[0].size();
if (S.size() < wordCount*wordSize)
return res;
unordered_map<string, int> mp, mp_copy;
for (int i=0;i<L.size();i++)
{
mp_copy[L[i]]++;
}
for (int start=0;start<=S.size()-wordCount*wordSize; ++start)
{
mp=mp_copy;
bool exist = true;
for (int j=0;j<wordCount;j++)
{
string cur = S.substr(start+j*wordSize, wordSize);
if (mp.find(cur)==mp.end() || mp[cur]<=0)
{
exist = false;
break;
}
else
{
mp[cur]--;
}
}
if (exist)
{
res.push_back(start);
}
}
return res;
}
};
No comments:
Post a Comment