天天看點

1668. 最大重複子字元串 LeetCode-字元串比對

LeetCode原題:1668. 最大重複子字元串

class Solution {
    public int maxRepeating(String sequence, String word) {
    	// 模式串長度大于原字元串,傳回0
        if (word.length() > sequence.length()) {
            return 0;
        }
        // 原字元串中一個模式串都沒有,傳回0
        if (sequence.indexOf(word) == -1) {
            return 0;
        }
        int index = sequence.indexOf(word);
        // 記錄從每個位置開始的模式串連續重複的次數
        int repeat = 0;
        // 記錄模式串最大連續重複次數
        int maxRepeat = 0;
        for (int i = index; i <= sequence.length() - word.length(); i++) {
        	// 從位置i開始(包含i以及i後面所有的位置)截取到字元串最後的位置,字元串長度已經比目前最長的連續模式串長度小,不需要繼續向下周遊計算
            if (sequence.length() - i <= maxRepeat * word.length()) {
                break;
            }
            repeat = 0;
            // 周遊檢查從位置i開始的模式串連續重複的次數
            for (int j = i, k = j + word.length(); k <= sequence.length(); j += word.length(), k += word.length()) {
                if (sequence.substring(j, k).equals(word)) {
                    repeat++;
                } else {
                    break;
                }
            }
            // 每次檢查完都更新最大連續重複次數
            maxRepeat = Math.max(maxRepeat, repeat);
        }
        return maxRepeat;
    }
}