Skip to content

📚 6.分割回文串

💻 代码实现

typescript
/**
 * @url https://leetcode.cn/problems/palindrome-partitioning/description/
 */

const isBackString = (str: string) => {
    return str === str.split("").reverse().join("")
}

function partition(s: string): string[][] {
    const result: string[][] = []
    const dfs = (startIdx: number, path: string[]) => {
        if (startIdx >= s.length) {
            result.push(path)
            return
        }
        for (let idx = startIdx; idx < s.length; idx++) {
            const str = s.slice(startIdx, idx + 1)
            if (isBackString(str)) {
                path.push(str)
                dfs(idx + 1, path.concat([]))
                path.pop()
            } else {
                continue
            }
        }
    }
    dfs(0, [])
    return result
}

Released under the MIT License.