LeetCodeSwift 集

LeetCode - #131 分割回文串

2022-10-06  本文已影响0人  Swift社区

前言

我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新到 128 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。

不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:中等

1. 描述

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

2. 示例

示例 1

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2

输入:s = "a"
输出:[["a"]]

约束条件:

3. 答案

class PalindromePartitioning {
    func partition(_ s: String) -> [[String]] {
        var paths = [[String]](), path = [String]()
        
        dfs(&paths, &path, Array(s), 0)
        
        return paths
    }
    
    fileprivate func dfs(_ paths: inout [[String]], _ path: inout [String], _ s: [Character], _ index: Int) {
        if index == s.count {
            paths.append(Array(path))
            return
        }
        
        for i in index..<s.count {
            let current = String(s[index...i])
            
            if current.isPalindrome {
                path.append(current)
                dfs(&paths, &path, s, i + 1)
                path.removeLast()
            }
        }
    }
}

extension String {
    var isPalindrome: Bool {
        let chars = Array(self)
        
        var i = 0, j = count - 1
        
        while i <= j {
            if chars[i] != chars[j] {
                return false
            }
            i += 1
            j -= 1
        }
        
        return true
    }
}

该算法题解的仓库:LeetCode-Swift

点击前往 LeetCode 练习

关于我们

我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。

后续还会翻译大量资料到我们公众号,有感兴趣的朋友,可以加入我们。

上一篇下一篇

猜你喜欢

热点阅读