File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed
lcof2/剑指 Offer II 020. 回文子字符串的个数 Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -145,6 +145,40 @@ func countSubstrings(s string) (ans int) {
145
145
}
146
146
```
147
147
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
+
148
182
<!-- tabs: end -->
149
183
150
184
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments