-
Notifications
You must be signed in to change notification settings - Fork 25
/
0459-repeated-substring-pattern.js
71 lines (51 loc) · 1.65 KB
/
0459-repeated-substring-pattern.js
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
// 459. Repeated Substring Pattern
// Easy 38%
// 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.)
/**
* @param {string} s
* @return {boolean}
*/
const repeatedSubstringPattern = function(s) {
const n = s.length
for (let i = 2; i <= n; i++) {
if (!(n % i)) {
let p = -1, q = n / i - 1
while (q < n && s[++p] === s[++q]);
if (q >= n) return true
}
}
return false
// // more easy solution
// return (s + s).slice(1, s.length * 2 - 1).includes(s)
}
;[
'abab', // true
'aba', // false
'abcabcabcabc', // true
'abac', // false
'ababab', // true
].forEach(s => {
console.log(repeatedSubstringPattern(s))
})
// Solution:
// 因为要重复两次及以上,所以从重复的次数开始入手。
// 从重复 2 次开始检查,不断递增,直到重复 n 次。
// 如果重复次数不能整除字符串长度,则跳过。
// 在能整除的次数中,从 p = [0, n / i],检查
// s[p]是否与 s[p + n / i]相同,如果全部都同,说明是重复子字符串组成。
// Submission Result: Accepted