查找给定字符串中的所有重复子字符串

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)的时间复杂度上实现上述问题?

如果您的答案是后缀树或哈希,请详细说明.

ipc*_*ipc 5

如果分析字符串的输出"AAAAAAAAAAAAAA",则其中有O(n²)个字符,因此算法至少为O(n²).

要实现O(n²),只需为s的每个后缀构建后缀树(indices [1..n],[2..n],[3..n],...,[n..n] ).如果其中一个字符串没有自己的结束节点,则只计算每个节点的使用频率并不重要.

最后,迭代计数> 1的每个节点并打印其路径.