Repeated Substring Pattern

题目地址:
https://leetcode.com/problems/repeated-substring-pattern/description/

题目:
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"

Output: False
Example 3:
Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

解题思路:
这道题可以用KMP解法来做。

代码:

public boolean repeatedSubstringPattern(String s) {
    int len = s.length();
    int[] array = new int[len];
    int i = 1;
    int j = 0;
    while(i <= len - 1){
        if(s.charAt(i) == s.charAt(j)){
            array[i] = j + 1;
            i++;
            j++;
        }
        else if(j == 0){
            array[i] = 0;
            i++;
        }
        else {
            j = array[j - 1];
        }
    }
    int patternLen = len - array[len - 1];
    if(patternLen != len && len % patternLen == 0){
        return true;
    }
    return false;
}



Comments

Popular Posts