-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathrepeated-substring-pattern.js
67 lines (62 loc) · 1.32 KB
/
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
/**
* 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.)
*/
/**
* Smart Solution
*
* @param {string} s
* @return {boolean}
*/
const repeatedSubstringPattern = s => {
const str = s + s;
return str.substring(1, str.length - 1).includes(s);
};
/**
* Recursive Solution
*
* @param {string} s
* @return {boolean}
*/
const repeatedSubstringPattern = s => {
const canRepeat = (s, rest) => {
if (s.length > rest.length) {
return false;
}
for (let i = 0; i < rest.length; i += s.length) {
if (rest.substr(i, s.length) !== s) {
return false;
}
}
return true;
};
for (let i = 0; i < s.length; i++) {
if (canRepeat(s.substr(0, i + 1), s.substr(i + 1))) {
return true;
}
}
return false;
};
export { repeatedSubstringPattern };