*LeetCode--Repeated Substring Pattern (自己的笨方法 & KMP算法)

Repeated Substring Pattern    

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.)
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        if(s == null || s.length() == 0) return false;
        int j = 1;
        for(; j * 2 <= s.length(); j++){
            System.out.println(s.charAt( j ));
            if(s.charAt(0) == s.charAt(j) && s.length() % j == 0 && s.substring(0, j).equals( s.substring(j, j * 2) )) {
                for(int i = 0; i + j <= s.length(); i += j ){
                    if(!s.substring(i, i + j).equals( s.substring(0, j))) break;
                    if(i + j == s.length()) return true;
                }

            }
        }
        return false;
    }
}

  

KMP方法的next数组,next数组的划分都是相等的整数倍,即true 否则为false

posted @ 2018-05-23 23:01  SkyeAngel  阅读(86)  评论(0编辑  收藏  举报