您的位置:首页 > 编程语言 > C语言/C++

LeetCode 29. Substring with Concatenation of All Words

2014-06-21 01:52 387 查看
暴力匹配。

用一张map统计L的单词及频数;

另一张map再迭代中记录自当前迭代下标begin起的子串的单词频数,当当前频数超过总频数时重新迭代:

if (++ tmp[S.substr(begin+i*word_size, word_size)] > cnt[S.substr(begin+i*word_size, word_size)] )
{
<span style="white-space:pre">	</span>break;
}


完整代码:

class Solution
{
public:
vector<int> findSubstring(string S, vector<string> &L)
{
if( L.empty() == true )
{
return vector<int>();
}
vector<int> ret;
map<string, int> cnt;
int word_size = L[0].size();
for (auto it = L.begin(); it != L.end(); ++ it)
{
++ cnt[*it];
}

for (int begin = 0; begin <= int(S.size())-int(L.size()*word_size); ++ begin)
{
map<string, int> tmp;
size_t i = 0;
for ( ; i < L.size(); ++ i)
{
if (++ tmp[S.substr(begin+i*word_size, word_size)] > cnt[S.substr(begin+i*word_size, word_size)] )
{
break;
}
}
if (i == L.size())
{
ret.push_back(begin);
}
}

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