Skip to content

Commit a1d0744

Browse files
committed
Repeated substring pattern.
1 parent 1293bf5 commit a1d0744

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
3+
4+
 
5+
6+
Example 1:
7+
Input: s = "abab"
8+
Output: true
9+
Explanation: It is the substring "ab" twice.
10+
11+
Example 2:
12+
Input: s = "aba"
13+
Output: false
14+
15+
Example 3:
16+
Input: s = "abcabcabcabc"
17+
Output: true
18+
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
19+
 
20+
21+
Constraints:
22+
- 1 <= s.length <= 104
23+
- s consists of lowercase English letters.
24+
*/
25+
class Solution {
26+
func repeatedSubstringPattern(_ s: String) -> Bool {
27+
let arr: [Character] = s.map { $0 }
28+
var i = 1
29+
var j = 0
30+
let n = s.count
31+
var dp: [Int] = Array(repeating: 0, count: n + 1)
32+
while i < n {
33+
if arr[i] == arr[j] {
34+
i += 1
35+
j += 1
36+
dp[i] = j
37+
} else if j == 0 {
38+
i += 1
39+
} else {
40+
j = dp[j]
41+
}
42+
}
43+
return dp[n] % (n - dp[n]) == 0 && dp[n] != 0
44+
}
45+
}
46+
47+
let s = Solution()
48+
let r = s.repeatedSubstringPattern("bb")
49+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/459.Repeated Substring Pattern.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
88. [Find All Numbers Disappeared in an Array](c)
9393
89. [Minimum Moves to Equal Array Elements](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/448.Minimum%20Moves%20toEqual%20Array%20Elements.playground/Contents.swift)
9494
90. [Assign Cookies](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/455.Assign%20Cookies.playground/Contents.swift)
95+
91. [Repeated Substring Pattern](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/459.Repeated%20Substring%20Pattern.playground/Contents.swift)
9596

9697
#### Medium
9798

0 commit comments

Comments
 (0)