package com.example.leetcode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* @description: 131. 分割回文串
* 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
* <p>
* 回文串 是正着读和反着读都一样的字符串。
* <p>
* <p>
* <p>
* 示例 1:
* <p>
* 输入:s = "aab"
* 输出:[["a","a","b"],["aa","b"]]
* 示例 2:
* <p>
* 输入:s = "a"
* 输出:[["a"]]
* @author: licm
* @create: 2021-05-06 16:05
**/
public class Lc131_分割回文串 {
/**
* 判断是否是回文数
*
* TODO 虽然不理解为什么用了字符数组可以,字符串截取就不行,但ac啦下次再看
* @param s
* @param begin
* @param end
* @return
*/
static boolean isPalindrom(char[] s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
public static List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
Deque<String> path = new ArrayDeque<>();
backtracking(s.toCharArray(), 0, res, path);
return res;
}
static void backtracking(char[] s, int startIndex, List<List<String>> res, Deque<String> path) {
if (startIndex == s.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length; i++) {
if (isPalindrom(s, startIndex, i)) {
path.addLast(new String(s,startIndex, i - startIndex + 1));
} else {
continue;
}
backtracking(s, i + 1, res, path);
path.removeLast();
}
}
public static void main(String[] args) {
String s = "aab";
List<List<String>> res = partition(s);
res.forEach(m -> {
for (String r : m) {
System.out.print(r + "");
}
System.out.println();
});
System.out.println();
}
}
Lc131_分割回文串
原创qq5924db5b70f63 ©著作权
©著作权归作者所有:来自51CTO博客作者qq5924db5b70f63的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:Lc_78子集
下一篇:Lc40_组合总和II

提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【达梦系列】分割字符串,返回表之(管道表函数)
文章分类没有达梦数据库,所以只能选择oracle了
字符串 自定义 自定义函数 -
LeetCode 131. 分割回文串
截止到目前我已经写了 500多道算法题,其中部分已经整理成了pdf文档,目前总共有1000多页(并且还会不断的增加)
leetcode 分割回文串 算法 字符串 子串 -
LeetCode 131. 分割回文串(回溯分割)
算法优化:先用dp算出所有子串是否是回文串,就不用频繁调用函数判断当前子串是否是回文串
leetcode 回文串 字符串 子串