Skip to content

Commit af17889

Browse files
committed
solve
1 parent c0ae96b commit af17889

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Solution {
2+
//dynamic programming
3+
// O(n^2) time / O(n^2) space
4+
func countSubstrings1(_ s: String) -> Int {
5+
var count = 0
6+
var characters = Array(s)
7+
var isPalindromes = Array(repeating: Array(repeating: false, count: characters.count), count: characters.count)
8+
9+
for i in 0..<characters.count {
10+
isPalindromes[i][i] = true
11+
count += 1
12+
}
13+
14+
for right in 1..<characters.count {
15+
for left in 0..<right {
16+
if characters[left] == characters[right]
17+
&& (isPalindromes[left+1][right-1] || right-left <= 2) {
18+
isPalindromes[left][right] = true
19+
count += 1
20+
}
21+
}
22+
}
23+
24+
return count
25+
}
26+
27+
//two pointers
28+
// O(n^2) time / O(n) space
29+
func countSubstrings2(_ s: String) -> Int {
30+
var count = 0
31+
var characters = Array(s)
32+
var left: Int
33+
var right: Int
34+
35+
for i in 0..<characters.count{
36+
left = i
37+
right = i
38+
39+
while left >= 0
40+
&& right < characters.count
41+
&& characters[left] == characters[right] {
42+
count += 1
43+
44+
left -= 1
45+
right += 1
46+
}
47+
48+
left = i
49+
right = i+1
50+
51+
while left >= 0
52+
&& right < characters.count
53+
&& characters[left] == characters[right] {
54+
count += 1
55+
56+
left -= 1
57+
right += 1
58+
}
59+
}
60+
61+
return count
62+
}
63+
64+
}
65+

0 commit comments

Comments
 (0)