diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 075734ea..47734f6c 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -450,7 +450,8 @@ var partition = function(s) { }; ``` -##C +## C + ```c char** path; 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 +} +``` + -----------------------