【发布时间】:2020-10-03 17:24:50
【问题描述】:
假设我有一个类似的字符串-
str = "cadaabaabbc";
所需的输出是 6,它占索引 3 到 8 的 "aabaab"。 有人可以从初学者的角度建议我一个有效的算法吗?
谢谢。
【问题讨论】:
标签: algorithm substring time-complexity
假设我有一个类似的字符串-
str = "cadaabaabbc";
所需的输出是 6,它占索引 3 到 8 的 "aabaab"。 有人可以从初学者的角度建议我一个有效的算法吗?
谢谢。
【问题讨论】:
标签: algorithm substring time-complexity
https://en.wikipedia.org/wiki/Suffix_array
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
class Node
{
public:
char ch;
unordered_map<char, Node *> children;
vector<int> indexes; //store the indexes of the substring from where it starts
Node(char c) : ch(c) {}
};
int maxLen = 0;
string maxStr = "";
void insertInSuffixTree(Node *root, string str, int index, string originalSuffix, int level = 0)
{
root->indexes.push_back(index);
// it is repeated and length is greater than maxLen
// then store the substring
if (root->indexes.size() > 1 && maxLen < level)
{
maxLen = level;
maxStr = originalSuffix.substr(0, level);
}
if (str.empty())
return;
Node *child;
if (root->children.count(str[0]) == 0)
{
child = new Node(str[0]);
root->children[str[0]] = child;
}
else
{
child = root->children[str[0]];
}
insertInSuffixTree(child, str.substr(1), index, originalSuffix, level + 1);
}
int main()
{
string str = "cadaabaabbc";//"missiissippi";
Node *root = new Node('@');
//insert all substring in suffix tree
for (int i = 0; i < str.size(); i++)
{
string s = str.substr(i);
insertInSuffixTree(root, s, i, s);
}
int startIndex = str.find(maxStr);
cout << startIndex << " to " << startIndex + (2 * maxLen) - 1;
return 1;
}
【讨论】: