File tree 2 files changed +73
-0
lines changed
lcof2/剑指 Offer II 087. 复原 IP
2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -288,6 +288,45 @@ public class Solution {
288
288
}
289
289
```
290
290
291
+ #### Swift
292
+
293
+ ``` swift
294
+ class Solution {
295
+ private var n: Int = 0
296
+ private var s: String = " "
297
+ private var ans: [String ] = []
298
+ private var t: [String ] = []
299
+
300
+ func restoreIpAddresses (_ s : String ) -> [String ] {
301
+ n = s.count
302
+ self .s = s
303
+ dfs (0 )
304
+ return ans
305
+ }
306
+
307
+ private func dfs (_ i : Int ) {
308
+ if i >= n && t.count == 4 {
309
+ ans.append (t.joined (separator : " ." ))
310
+ return
311
+ }
312
+ if i >= n || t.count >= 4 {
313
+ return
314
+ }
315
+ var x = 0
316
+ let chars = Array (s)
317
+ for j in i..< min (i + 3 , n) {
318
+ x = x * 10 + Int (chars[j].wholeNumberValue ! )
319
+ if x > 255 || (chars[i] == " 0" && i != j) {
320
+ break
321
+ }
322
+ t.append (String (chars[i... j ]))
323
+ dfs (j + 1 )
324
+ t.removeLast ()
325
+ }
326
+ }
327
+ }
328
+ ```
329
+
291
330
<!-- tabs: end -->
292
331
293
332
<!-- 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 ans : [ String ] = [ ]
5
+ private var t : [ String ] = [ ]
6
+
7
+ func restoreIpAddresses( _ s: String ) -> [ String ] {
8
+ n = s. count
9
+ self . s = s
10
+ dfs ( 0 )
11
+ return ans
12
+ }
13
+
14
+ private func dfs( _ i: Int ) {
15
+ if i >= n && t. count == 4 {
16
+ ans. append ( t. joined ( separator: " . " ) )
17
+ return
18
+ }
19
+ if i >= n || t. count >= 4 {
20
+ return
21
+ }
22
+ var x = 0
23
+ let chars = Array ( s)
24
+ for j in i..< min ( i + 3 , n) {
25
+ x = x * 10 + Int( chars [ j] . wholeNumberValue!)
26
+ if x > 255 || ( chars [ i] == " 0 " && i != j) {
27
+ break
28
+ }
29
+ t. append ( String ( chars [ i... j] ) )
30
+ dfs ( j + 1 )
31
+ t. removeLast ( )
32
+ }
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments