diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 2277aa60..5118810d 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -66,10 +66,10 @@ startIndex一定是需要的,因为不能重复分割,记录下一层递归 所以代码如下: -``` - vector result;// 记录结果 - // startIndex: 搜索的起始位置,pointNum:添加逗点的数量 - void backtracking(string& s, int startIndex, int pointNum) { +```cpp +vector result;// 记录结果 +// startIndex: 搜索的起始位置,pointNum:添加逗点的数量 +void backtracking(string& s, int startIndex, int pointNum) { ``` * 递归终止条件 @@ -82,7 +82,7 @@ pointNum表示逗点数量,pointNum为3说明字符串分成了4段了。 代码如下: -``` +```cpp if (pointNum == 3) { // 逗点数量为3时,分隔结束 // 判断第四段子字符串是否合法,如果合法就放进result中 if (isValid(s, startIndex, s.size() - 1)) { @@ -96,7 +96,7 @@ if (pointNum == 3) { // 逗点数量为3时,分隔结束 在[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)中已经讲过在循环遍历中如何截取子串。 -在`for (int i = startIndex; i < s.size(); i++)`循环中 [startIndex, i]这个区间就是截取的子串,需要判断这个子串是否合法。 +在`for (int i = startIndex; i < s.size(); i++)`循环中 [startIndex, i] 这个区间就是截取的子串,需要判断这个子串是否合法。 如果合法就在字符串后面加上符号`.`表示已经分割。 @@ -531,6 +531,53 @@ char ** restoreIpAddresses(char * s, int* returnSize){ } ``` +## Swift + +```swift +// 判断区间段是否合法 +func isValid(s: [Character], start: Int, end: Int) -> Bool { + guard start <= end, start >= 0, end < s.count else { return false } // 索引不合法 + if start != end, s[start] == "0" { return false } // 以0开头的多位数字不合法 + var num = 0 + for i in start ... end { + let c = s[i] + guard c >= "0", c <= "9" else { return false } // 非数字不合法 + let value = c.asciiValue! - ("0" as Character).asciiValue! + num = num * 10 + Int(value) + guard num <= 255 else { return false } // 大于255不合法 + } + return true +} +func restoreIpAddresses(_ s: String) -> [String] { + var s = Array(s) // 转换成字符数组以便于比较 + var result = [String]() // 结果 + func backtracking(startIndex: Int, pointCount: Int) { + guard startIndex < s.count else { return } // 索引不合法 + // 结束条件 + if pointCount == 3 { + // 最后一段也合法,则收集结果 + if isValid(s: s, start: startIndex, end: s.count - 1) { + result.append(String(s)) + } + return + } + + for i in startIndex ..< s.count { + // 判断[starIndex, i]子串是否合法,合法则插入“.”,否则结束本层循环 + if isValid(s: s, start: startIndex, end: i) { + s.insert(".", at: i + 1) // 子串后面插入“.” + backtracking(startIndex: i + 2, pointCount: pointCount + 1) // 注意这里时跳2位,且通过pointCount + 1局部变量隐藏了pointCount的回溯 + s.remove(at: i + 1) // 回溯 + } else { + break + } + } + } + backtracking(startIndex: 0, pointCount: 0) + return result +} +``` + -----------------------