0131.分割回文串:优化排版,补充Swift版本

This commit is contained in:
bqlin
2021-12-12 12:54:37 +08:00
parent 9a577c7b25
commit c82bf133d4

View File

@ -450,7 +450,8 @@ var partition = function(s) {
}; };
``` ```
##C ## C
```c ```c
char** path; char** path;
int pathTop; int pathTop;
@ -546,5 +547,48 @@ char*** partition(char* s, int* returnSize, int** returnColumnSizes){
} }
``` ```
## Swift
```swift
func partition(_ s: String) -> [[String]] {
// 把字符串转为字符数组以便于通过索引访问和取子串
let s = Array(s)
// 使用双指针法判断子串是否回文
func isPalindrome(start: Int, end: Int) -> Bool {
var start = start, end = end
while start < end {
if s[start] != s[end] { return false }
start += 1
end -= 1
}
return true
}
var result = [[String]]()
var path = [String]() // 切割方案
func backtracking(startIndex: Int) {
// 终止条件,收集结果
guard startIndex < s.count else {
result.append(path)
return
}
for i in startIndex ..< s.count {
// 回文则收集,否则跳过
if isPalindrome(start: startIndex, end: i) {
let substring = String(s[startIndex ... i])
path.append(substring)
} else {
continue
}
backtracking(startIndex: i + 1) // 寻找下一个起始位置的子串
if !path.isEmpty { path.removeLast() } // 回溯
}
}
backtracking(startIndex: 0)
return result
}
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>