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) // 2pointCount + 1pointCount
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>