【问题标题】:How to find the length of the longest substring such that it is repeated consecutively如何找到最长子串的长度,使其连续重复
【发布时间】:2020-10-03 17:24:50
【问题描述】:

假设我有一个类似的字符串-

str = "cadaabaabbc";

所需的输出是 6,它占索引 38"aabaab"。 有人可以从初学者的角度建议我一个有效的算法吗?

谢谢。

【问题讨论】:

    标签: algorithm substring time-complexity


    【解决方案1】:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-19
      • 2017-05-30
      • 2014-07-20
      • 2016-08-11
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2012-05-08
      相关资源
      最近更新 更多