File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
lcof2/剑指 Offer II 086. 分割回文子字符串 Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change @@ -285,6 +285,49 @@ public class Solution {
285
285
}
286
286
```
287
287
288
+ #### Swift
289
+
290
+ ``` swift
291
+ class Solution {
292
+ private var n: Int = 0
293
+ private var s: String = " "
294
+ private var f: [[Bool ]] = []
295
+ private var t: [String ] = []
296
+ private var ans: [[String ]] = []
297
+
298
+ func partition (_ s : String ) -> [[String ]] {
299
+ n = s.count
300
+ self .s = s
301
+ f = Array (repeating : Array (repeating : true , count : n), count : n)
302
+
303
+ let chars = Array (s)
304
+
305
+ for i in stride (from : n - 1 , through : 0 , by : -1 ) {
306
+ for j in i + 1 ..< n {
307
+ f[i][j] = chars[i] == chars[j] && f[i + 1 ][j - 1 ]
308
+ }
309
+ }
310
+
311
+ dfs (0 )
312
+ return ans
313
+ }
314
+
315
+ private func dfs (_ i : Int ) {
316
+ if i == n {
317
+ ans.append (t)
318
+ return
319
+ }
320
+ for j in i ..< n {
321
+ if f[i][j] {
322
+ t.append (String (s[s.index (s.startIndex , offsetBy : i)... s .index (s.startIndex , offsetBy : j)]))
323
+ dfs (j + 1 )
324
+ t.removeLast ()
325
+ }
326
+ }
327
+ }
328
+ }
329
+ ```
330
+
288
331
<!-- tabs: end -->
289
332
290
333
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var n : Int = 0
3
+ private var s : String = " "
4
+ private var f : [ [ Bool ] ] = [ ]
5
+ private var t : [ String ] = [ ]
6
+ private var ans : [ [ String ] ] = [ ]
7
+
8
+ func partition( _ s: String ) -> [ [ String ] ] {
9
+ n = s. count
10
+ self . s = s
11
+ f = Array ( repeating: Array ( repeating: true , count: n) , count: n)
12
+
13
+ let chars = Array ( s)
14
+
15
+ for i in stride ( from: n - 1 , through: 0 , by: - 1 ) {
16
+ for j in i + 1 ..< n {
17
+ f [ i] [ j] = chars [ i] == chars [ j] && f [ i + 1 ] [ j - 1 ]
18
+ }
19
+ }
20
+
21
+ dfs ( 0 )
22
+ return ans
23
+ }
24
+
25
+ private func dfs( _ i: Int ) {
26
+ if i == n {
27
+ ans. append ( t)
28
+ return
29
+ }
30
+ for j in i ..< n {
31
+ if f [ i] [ j] {
32
+ t. append ( String ( s [ s. index ( s. startIndex, offsetBy: i) ... s. index ( s. startIndex, offsetBy: j) ] ) )
33
+ dfs ( j + 1 )
34
+ t. removeLast ( )
35
+ }
36
+ }
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments