【发布时间】:2012-04-20 18:04:46
【问题描述】:
我最近遇到一个面试问题: 查找给定字符串中最小大小为 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"));
}
我的问题是,有没有什么数据结构可以及时实现上述问题 O(N)的复杂度?
如果您的答案是后缀树或散列,请详细说明。
【问题讨论】:
-
如果我理解正确,您认为输出中的两个(大小相等)子字符串不同,如果它们的起始索引不同,而不是它们的内容不同,对吧?
-
阅读后缀树,在我看来,wiki 是一个好的开始:en.wikipedia.org/wiki/Suffix_tree
-
@dexametason 您正在建议最好的解决方案。重复的子字符串是 CS 中非常常见的问题。您能否将此作为解决方案发布?这将对网站访问者非常有帮助。干杯!
-
@MonsterTruck 因为我看到接受的答案在我的评论之后包含相同的内容,所以我不想重复它作为答案。也许应该将某些链接添加到已接受的答案中。