Ind*_*mer 13 c++ string algorithm
我刚接触到一个采访问题:找到一个给定字符串中所有重复的子字符串,其最小大小为2.该算法应该是高效的.
上面给出了上述问题的代码,但效率不高.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <set>
#include <string>
using namespace std;
int main()
{
typedef string::const_iterator iterator;
string s("ABCFABHYIFAB");
set<string> found;
if (2 < s.size())
for (iterator i = s.begin() + 1, j = s.end(); i != j; ++i)
for (iterator x = s.begin(); x != i; ++x)
{
iterator tmp = mismatch(i, j, x).second;;
if (tmp - x > 1)
found.insert(string(x, tmp));
}
copy(found.begin(), found.end(),ostream_iterator<string>(cout, "\n"));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否有任何数据结构可以在O(N)的时间复杂度上实现上述问题?
如果您的答案是后缀树或哈希,请详细说明.
归档时间: |
|
查看次数: |
11386 次 |
最近记录: |