20221103 - 1668. Maximum Repeating Substring 最大重复子字符串(KMP)

62 阅读1分钟

For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.

Given strings sequence and word, return the maximum k-repeating value of word in sequence.

Example 1

Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in "ababc".

Example 2

Input: sequence = "ababc", word = "ba"
Output: 1
Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".

Example 3

Input: sequence = "ababc", word = "ac"
Output: 0
Explanation: "ac" is not a substring in "ababc". 

Constraints

  • 1 <= sequence.length <= 100
  • 1 <= word.length <= 100
  • sequence and word contains only lowercase English letters.

Solution

默写 KMP

class Solution {
public:
    void buildMatch(vector<int> &match, string pattern) {
        match[0] = -1;
        for (int i = 1; i < match.size(); i++) {
            int j = match[i - 1];
            while (j >= 0 && pattern[i] != pattern[j + 1])
                j = match[j];
            if (pattern[i] == pattern[j + 1]) match[i] = j + 1;
            else match[i] = -1;
        }
    }
    int KMP(string sstring, string pattern) {
        int n = sstring.length();
        int m = pattern.length();
        if (n < m) return -1;
        vector<int> match(m);
        buildMatch(match, pattern);
        int s, p;
        s = p = 0;
        while (s < n && p < m) {
            if (sstring[s] == pattern[p]) {
                s++; p++;
            } else if (p > 0)
                p = match[p - 1] + 1;
            else
                s++;
        }
        return (p == m) ? s - m : -1;
    }
    int maxRepeating(string sequence, string word) {
        int ans = 0;
        string pattern = word;
        while (KMP(sequence, pattern) != -1) {
            ans++;
            pattern += word;
        }
        return ans;
    }
};

题目链接:1668. 最大重复子字符串 - 力扣(LeetCode)