剑指offer_086 分割回文字符串
作者:互联网
题目:
给定一个字符串 s ,请将 s 分割成一些子串,使每个子串都是 回文串 ,返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "google"
输出:[["g","o","o","g","l","e"],["g","oo","g","l","e"],["goog","l","e"]]
示例 2:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 3:
输入:s = "a"
输出:[["a"]]
提示:
1 <= s.length <= 16
s 仅由小写英文字母组成
代码:
class Solution {
List<List<String>> res = new ArrayList<>();
List<String> temp = new ArrayList<>();
String str;
int n;
public String[][] partition(String s) {
str = s;
n = s.length();
dfs(0);
String[][] ans = new String[res.size()][];
for (int i = 0; i < res.size(); i++) {
List<String> list = res.get(i);
String[] str1 = new String[list.size()];
for (int j = 0; j < list.size(); j++) {
str1[j] = list.get(j);
}
ans[i] = str1;
}
return ans;
}
public void dfs(int index) {
if (index == n) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = index; i < n; i++) {
String s1 = str.substring(index, i+1);
if (check(s1)) {
temp.add(s1);
dfs(i + 1);
temp.remove(temp.size() - 1);
}
}
}
public boolean check(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
解题思路:
回溯,注意返回的是二维数组,并不是集合。
注意:
早睡早起。
参考链接:
标签:String,offer,int,res,086,str,new,size,回文 来源: https://blog.csdn.net/weixin_43817702/article/details/123245578