Skip to content

Commit c0815c2

Browse files
authored
feat: add swift implementation to lcof2 problem: No.087 (#3472)
1 parent d499e62 commit c0815c2

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

lcof2/剑指 Offer II 087. 复原 IP/README.md

+39
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,45 @@ public class Solution {
288288
}
289289
```
290290

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+
291330
<!-- tabs:end -->
292331

293332
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)