- 题目链接:131. 分割回文串 - 力扣(LeetCode): https://leetcode.cn/problems/palindrome-partitioning/
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
1 <= s.length <= 16
s 仅由小写英文字母组成
示例1
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例2
输入:s = "a"
输出:[["a"]]
import java.util.ArrayList;
import java.util.List;
public class LeetCode131_01_01 {
public List<List<String>> ret = new ArrayList<>();
public List<String> tempList = new ArrayList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return ret;
}
public void backTracking(String s, int startIndex) {
if (startIndex >= s.length()) {
ret.add(new ArrayList<>(tempList));
return;
}
// i 负责控制截取子串的长度
// startIndex + i 的最大值需要等于 s.length()
// 所以 i <= s.length - startIndex
for (int i = 1; i <= s.length() - startIndex; i++) {
String tempStr = s.substring(startIndex, startIndex + i);
if (judgePalindrome(tempStr)) {
tempList.add(tempStr);
} else {
continue;
}
// 截取时,左闭右开,所以下一轮从 startIndex + 1 开始
backTracking(s, startIndex + i);
tempList.remove(tempList.size() - 1);
}
}
// 判断是否为回文串
public boolean judgePalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++;
j--;
}
return true;
}
}
略有些惭愧,发现还是第一次做这题的时候,思路清晰。
下图,我提取了回溯函数部分的大致思路;
我觉得最主要的还是关于回文串的判断,
