diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" index 68621fb5d7e99..6d2ad9326d3dc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" @@ -288,6 +288,45 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + private var n: Int = 0 + private var s: String = "" + private var ans: [String] = [] + private var t: [String] = [] + + func restoreIpAddresses(_ s: String) -> [String] { + n = s.count + self.s = s + dfs(0) + return ans + } + + private func dfs(_ i: Int) { + if i >= n && t.count == 4 { + ans.append(t.joined(separator: ".")) + return + } + if i >= n || t.count >= 4 { + return + } + var x = 0 + let chars = Array(s) + for j in i.. 255 || (chars[i] == "0" && i != j) { + break + } + t.append(String(chars[i...j])) + dfs(j + 1) + t.removeLast() + } + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.swift" new file mode 100644 index 0000000000000..bd98392ad19e7 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/Solution.swift" @@ -0,0 +1,34 @@ +class Solution { + private var n: Int = 0 + private var s: String = "" + private var ans: [String] = [] + private var t: [String] = [] + + func restoreIpAddresses(_ s: String) -> [String] { + n = s.count + self.s = s + dfs(0) + return ans + } + + private func dfs(_ i: Int) { + if i >= n && t.count == 4 { + ans.append(t.joined(separator: ".")) + return + } + if i >= n || t.count >= 4 { + return + } + var x = 0 + let chars = Array(s) + for j in i.. 255 || (chars[i] == "0" && i != j) { + break + } + t.append(String(chars[i...j])) + dfs(j + 1) + t.removeLast() + } + } +} \ No newline at end of file