1. 程式人生 > 其它 >leetcode 459. 重複的子字串

leetcode 459. 重複的子字串

給定一個非空的字串,判斷它是否可以由它的一個子串重複多次構成。給定的字串只含有小寫英文字母,並且長度不超過10000。

示例 1:

輸入: "abab"

輸出: True

解釋: 可由子字串 "ab" 重複兩次構成。
示例 2:

輸入: "aba"

輸出: False
示例 3:

輸入: "abcabcabcabc"

輸出: True

解釋: 可由子字串 "abc" 重複四次構成。 (或者子字串 "abcabc" 重複兩次構成。)

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/repeated-substring-pattern
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

1:獲取字串最後一個字元 end, 遍歷字串,尋找==end的索引位置位n。

2:把 從0 到n的字串當作潛在的子串str。從n之後遍歷 是否都是str的迴圈。

  

    public boolean repeatedSubstringPattern(String s) {
        int length = s.length();
        char[] arr = s.toCharArray();

        char end =arr[length - 1];
        int n = find(0,arr,  end);

        int index = 0;
        
for (int i = n; i < length; i++) { if (arr[i] != arr[index++]) { n = find(i - index + 1, arr, end); i = n - 1; index = 0; } if (index == n) { index = 0; } } return n != length; }
private int find(int start, char[] arr, char end) { int length = arr.length; int n = 1; for (int i = start; i < length; i++) { if (arr[i] == end && length % (i + 1) == 0) { n = i + 1; break; } } return n; }

若不是,則從n 之後繼續尋找值為end的位置,替換為n,重複上面步驟。

3:最後判斷n != length並返回。