这个题目的难点是分割,然后思路的话,还是比较常规,回溯就行
注意需要使用一个start去记录左边界,那么右边界就是i,因为左边的start是上一个的结束位置
代码如下:
package com.codeking.lc;
import java.util.ArrayList;
import java.util.List;
/**
* @author xiongjl
* @since 2023/9/22 16:04
*/
public class lc131 {
public static void main(String[] args) {
lc131 lc131 = new lc131();
List<List<String>> efe = lc131.partition("efe");
System.out.println(efe);
}
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
backTracing(res, new ArrayList<>(), s, 0);
return res;
}
void backTracing(List<List<String>> res, List<String> cur,String s,int start) {
if (start==s.length()) {
res.add(new ArrayList<>(cur));
}
for (int i = start; i < s.length(); i++) {
// 分割字符串
String temp = s.substring(start, i+1);
// 直接判断是不是回文
if (isPalindrome(temp)) {
cur.add(temp);
backTracing(res, cur, s, i+1);
cur.remove(cur.size() - 1);
}
}
}
// 写一个判断回文子串
boolean isPalindrome(String s) {
char[] str = s.toCharArray();
// 前后遍历就行
for (int i = 0; i <= str.length / 2; i++) {
int start = str[i];
int end = str[str.length - 1 - i];
if (start != end) {
return false;
}
}
return true;
}
}