459.repeated-substring-pattern 重复的子串

2022/8/15 23:29:55

本文主要是介绍459.repeated-substring-pattern 重复的子串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

假设一个字符串,是由一个重复的子串组成的,那么它的最长相等前后缀必然与整个字符串的必然相差了一个重复子串的长度。
假设整个字符串的长度为len,那么next[len - 1] + 1就是最长相等前后缀的长度,且len % (len - next[len - 1] + 1) == 0

class Solution {
  public:
    void getNext(int *next, const string &s) {
        int j = -1;
        next[0] = j;
        for (int i = 1; i < s.size(); i++) {
            // next[j + 1]指向匹配好的前缀的下一个字符
            // i指向后缀末尾位置
            while (j >= 0 && s[i] != s[j + 1]) {
                j = next[j];
            }
            if (s[i] == s[j + 1]) {
                j++;
            }
            next[i] = j;
        }
    }
    bool repeatedSubstringPattern(string s) {
        // string s2 = s + s;
        int next[s.size()];
        int len = s.size();
        int count = 0;
        getNext(next, s);
		//还要判断是否有最长相等前后缀
        if (next[len - 1] != -1 && len % (len - next[len - 1] - 1) == 0)
            return true;
        else
            return false;
    }
};


这篇关于459.repeated-substring-pattern 重复的子串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程