Skip to content

Commit baf5438

Browse files
authored
feat: add swift implementation to lcof2 problem: No.020 (#3008)
1 parent 2e351b8 commit baf5438

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

lcof2/剑指 Offer II 020. 回文子字符串的个数/README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,40 @@ func countSubstrings(s string) (ans int) {
145145
}
146146
```
147147

148+
#### Swift
149+
150+
```swift
151+
class Solution {
152+
private var s: String = ""
153+
154+
func countSubstrings(_ s: String) -> Int {
155+
var ans = 0
156+
self.s = s
157+
let length = s.count
158+
for i in 0..<length {
159+
ans += countPalindromes(i, i)
160+
ans += countPalindromes(i, i + 1)
161+
}
162+
return ans
163+
}
164+
165+
private func countPalindromes(_ i: Int, _ j: Int) -> Int {
166+
var cnt = 0
167+
var i = i
168+
var j = j
169+
let chars = Array(s)
170+
171+
while i >= 0 && j < chars.count && chars[i] == chars[j] {
172+
cnt += 1
173+
i -= 1
174+
j += 1
175+
}
176+
177+
return cnt
178+
}
179+
}
180+
```
181+
148182
<!-- tabs:end -->
149183

150184
<!-- solution:end -->
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
private var s: String = ""
3+
4+
func countSubstrings(_ s: String) -> Int {
5+
var ans = 0
6+
self.s = s
7+
let length = s.count
8+
for i in 0..<length {
9+
ans += countPalindromes(i, i)
10+
ans += countPalindromes(i, i + 1)
11+
}
12+
return ans
13+
}
14+
15+
private func countPalindromes(_ i: Int, _ j: Int) -> Int {
16+
var cnt = 0
17+
var i = i
18+
var j = j
19+
let chars = Array(s)
20+
21+
while i >= 0 && j < chars.count && chars[i] == chars[j] {
22+
cnt += 1
23+
i -= 1
24+
j += 1
25+
}
26+
27+
return cnt
28+
}
29+
}

0 commit comments

Comments
 (0)