- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathRepeatedSubstringPattern459.java
More file actions
Latest commit
89 lines (78 loc) · 2.41 KB
/
Copy pathRepeatedSubstringPattern459.java
File metadata and controls
89 lines (78 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* 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.)
*/
publicclassRepeatedSubstringPattern459 {
/**
* https://leetcode.com/problems/repeated-substring-pattern/discuss/94352/Java-Simple-Solution-with-Explanation
*/
publicbooleanrepeatedSubstringPattern(Strings) {
if(s==null || s.length()<=1) returnfalse;
for(inti=1;i<=s.length()/2;i++){
if(s.length()%i!=0) continue;
Stringsub = s.substring(0,i);
if(dfs(s,sub,i)) returntrue;
}
returnfalse;
}
privatebooleandfs(Strings,Stringsub,inti){
if(i==s.length()) returntrue;
if(!s.startsWith(sub,i)) returnfalse;
returndfs(s,sub,i+sub.length());
}
/**
* https://leetcode.com/problems/repeated-substring-pattern/discuss/94344/Simple-Java-solution-2-lines
*/
publicbooleanrepeatedSubstringPattern2(Stringstr) {
Strings = str + str;
returns.substring(1, s.length() - 1).contains(str);
}
/**
* https://leetcode.com/problems/repeated-substring-pattern/discuss/94340/Java-and-O(n)
*/
publicbooleanrepeatedSubstringPattern3(Stringstr) {
//This is the kmp issue
int[] prefix = kmp(str);
intlen = prefix[str.length()-1];
intn = str.length();
return (len > 0 && n%(n-len) == 0);
}
privateint[] kmp(Strings){
intlen = s.length();
int[] res = newint[len];
char[] ch = s.toCharArray();
inti = 0, j = 1;
res[0] = 0;
while(i < ch.length && j < ch.length){
if(ch[j] == ch[i]){
res[j] = i+1;
i++;
j++;
}else{
if(i == 0){
res[j] = 0;
j++;
}else{
i = res[i-1];
}
}
}
returnres;
}
}