-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0093_restore_ip_addresses.swift
60 lines (56 loc) · 1.74 KB
/
0093_restore_ip_addresses.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// https://leetcode.com/problems/restore-ip-addresses/description/
class Solution {
var result = [String]()
func restoreIpAddresses(_ s: String) -> [String] {
let chars = Array(s)
check(prevS: "", restCount: 4, restChars: chars)
return result
}
func check(prevS: String, restCount: Int, restChars: [Character]) {
var restChars = restChars
if restChars.isEmpty {
return
}
if restCount == 1 {
let s = String(restChars)
if isValid(s) {
result.append(prevS + s)
}
} else {
var s = String(restChars.removeFirst())
if isValid(s) {
check(prevS: prevS + s + ".", restCount: restCount - 1, restChars: restChars)
}
if !restChars.isEmpty {
s.append(restChars.removeFirst())
if isValid(s) {
check(prevS: prevS + s + ".", restCount: restCount - 1, restChars: restChars)
}
}
if !restChars.isEmpty {
s.append(restChars.removeFirst())
if isValid(s) {
check(prevS: prevS + s + ".", restCount: restCount - 1, restChars: restChars)
}
}
}
}
func isValid(_ s: String) -> Bool {
if s.count > 1 {
if s.count > 3 {
return false
} else if s.first! == "0" {
return false
} else {
let i = Int(s)!
if i > 255 {
return false
} else {
return true
}
}
} else {
return true
}
}
}