【LeetCode】131. Palindrome Partitioning 分割回文串(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
题目大意
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
解题方法
- 当前 string 开始遍历,判断前面的 n 个字符是否是回文串,如果是就通过递归把后续子串的分割方案返回
- 要注意如果当前整个字符串都是回文串的话,后续没有子串了,就把当前结果整个保存进 list 里面
- note: 后续可以对时间优化: 把遍历过 string 用 map 存起来,减少再次遍历
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (!check(s, 0, i)) continue;
if (i == s.length() - 1) {
List<String> list = new ArrayList<>();
list.add(s);
res.add(list);
continue;
}
String cur = s.substring(0, i + 1);
List<List<String>> next = partition(s.substring(i + 1, s.length()));
for (int j = 0; j < next.size(); j++) {
next.get(j).add(0, cur);
res.add(next.get(j));
}
}
return res;
}
public boolean check(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) return false;
start++;
end--;
}
return true;
}
}
执行耗时:5 ms,击败了31.55% 的Java用户
内存消耗:39.4 MB,击败了87.82% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)