459. 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.)

链接:https://leetcode.com/problems/repeated-substring-pattern/#/description

3/26/2017

没做出来,看的别人的答案,这个思路是我最开始想到的,但是没有写代码。

https://discuss.leetcode.com/topic/67992/java-simple-solution-with-explanation/3

思想是找因子,如果按因子大小分开的每个substring都是一样的,返回true

 1 public class Solution {
 2     public boolean repeatedSubstringPattern(String s) {
 3         
 4         for (int i = s.length()/2; i >= 1; i--) {
 5             if (s.length() % i == 0) {
 6                 int patternNumber = s.length() / i;
 7                 String t = s.substring(0, i);
 8                 int j;
 9                 for (j = 1; j < patternNumber; j++) {
10                     String t1 = s.substring(i*j, i*(j + 1));
11                     if (!t.equals(t1)) break;
12                 }
13                 if (j == patternNumber) return true;
14             }
15         }
16         return false;
17     }
18 }

还有很厉害的KMP数组的算法:

https://discuss.leetcode.com/topic/67590/java-o-n

 1 public boolean repeatedSubstringPattern(String str) {
 2             //This is the kmp issue
 3             int[] prefix = kmp(str);
 4             int len = prefix[str.length()-1];
 5             int n = str.length();
 6             return (len > 0 && n%(n-len) == 0);
 7         }
 8         private int[] kmp(String s){
 9             int len = s.length();
10             int[] res = new int[len];
11             char[] ch = s.toCharArray();
12             int i = 0, j = 1;
13             res[0] = 0;
14             while(i < ch.length && j < ch.length){
15                 if(ch[j] == ch[i]){
16                     res[j] = i+1;
17                     i++;
18                     j++;
19                 }else{
20                     if(i == 0){
21                         res[j] = 0;
22                         j++;
23                     }else{
24                         i = res[i-1];
25                     }
26                 }
27             }
28             return res;
29         }

更多讨论:

https://discuss.leetcode.com/category/587/repeated-substring-pattern

posted @ 2017-03-27 10:29  panini  阅读(183)  评论(0编辑  收藏  举报