0093.复原IP地址:优化排版,补充Swift版本

This commit is contained in:
bqlin
2021-12-12 17:08:20 +08:00
parent c82bf133d4
commit c29f74dc69

View File

@ -66,10 +66,10 @@ startIndex一定是需要的因为不能重复分割记录下一层递归
所以代码如下:
```
vector<string> result;// 记录结果
// startIndex: 搜索的起始位置pointNum:添加逗点的数量
void backtracking(string& s, int startIndex, int pointNum) {
```cpp
vector<string> 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
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>