forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
459_Repeated_Substring_Pattern
60 lines (49 loc) · 1.33 KB
/
459_Repeated_Substring_Pattern
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
Leetcode 459: Repeated Substring Pattern
Detailed video Explanation: https://youtu.be/p92_kEjyJAo
=============================================
C++:
----
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.length();
vector<int> lps(n, 0);
for(int i = 1; i < n; ++i){
int j = lps[i-1];
while(j > 0 && s[i] != s[j]) j = lps[j-1];
if(s[i] == s[j]) ++j;
lps[i] = j;
}
int l = lps[n-1];
return (l != 0) && (l % (n-l) == 0);
}
};
Java:
-----
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
int[] lps = new int[n];
for(int i = 1; i < n; ++i){
int j = lps[i-1];
while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j-1];
if(s.charAt(i) == s.charAt(j)) ++j;
lps[i] = j;
}
int l = lps[n-1];
return (l != 0) && (l % (n-l) == 0);
}
}
Python3:
--------
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
lps = [0]*n
for i in range(1, n):
j = lps[i-1]
while j > 0 and s[i] != s[j]: j = lps[j-1]
if s[i] == s[j]: j += 1
lps[i] = j
l = lps[n-1]
return l != 0 and (l % (n-l) == 0)