Leecode 0131. Palindrome Partitioning
131. Palindrome Partitioning
Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
Example 1:
1 | Input: s = "aab" |
Example 2:
1 | Input: s = "a" |
题目大意
给定一个字符串 s
,将其分割成若干个子串,使得每个子串都是回文串。返回所有可能的分割方案。
例如:
- 输入
s = "aab"
,输出[["a","a","b"],["aa","b"]]
(两种分割方式,每个子串都是回文); - 输入
s = "a"
,输出[["a"]]
(仅一种分割方式)。
解题思路
核心思路是递归回溯 + 回文判断,通过逐步划分字符串寻找所有有效分割方案:
递归状态设计
- 递归函数
dfs(i, start)
表示:处理到字符串第i
个字符,当前正在构建的回文子串从start
位置开始 path
存储当前分割方案,ans
存储所有有效方案
- 递归函数
核心决策逻辑
不分割:不在
i
和i+1
之间添加分割符,继续处理下一个字符(i+1
),当前子串的起始位置仍为start
分割:在
i
和i+1
之间添加分割符,此时需判断s[start..i]
是否为回文串:- 若是,则将该子串加入
path
,并开始构建下一个子串(起始位置设为i+1
) - 递归返回后回溯,移除刚加入的子串
- 若是,则将该子串加入
终止条件
- 当
i == n
(处理完所有字符)时,说明已完成一次有效分割,将path
加入结果列表
- 当
回文判断
- 辅助函数
is_palindrome
通过双指针法判断s[left..right]
是否为回文串 - 左右指针从两端向中间移动,若所有对应字符相等则为回文
- 辅助函数
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.