From c82bf133d4d6f95212ab42bfbcdb6af68927d9df Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 12 Dec 2021 12:54:37 +0800 Subject: [PATCH] =?UTF-8?q?0131.=E5=88=86=E5=89=B2=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E4=B8=B2=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C?= =?UTF-8?q?=E8=A1=A5=E5=85=85Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 46 +++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) 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 +} +``` + -----------------------