您的位置:首页 > 其它

[*leetcode 30] Substring with Concatenation of All Words

2015-04-12 22:44 543 查看
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).

[Solution]

vector<int> findSubstring(string S, vector<string> &L)
{
map<string, int> wcount;
vector<int> result;
int i = 0, j = 0;
if (L.size() == 0)
return result;

int len = L[0].size(), lsize = L.size();
for (i = 0; i < L.size(); i++)
wcount[L[i]]++;

for (i = 0; i <= (int)(S.size() - len * lsize); i++)
{
map<string, int> table;
for (j = 0; j < lsize; j++)
{
string word = S.substr(i + j * len, len);
if (wcount.find(word) == wcount.end())
break;
table[word]++;
if (table[word] > wcount[word])
break;
}
if (j == lsize)
result.push_back(i);
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: