Backtracking_131. 分割回文串

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning


思路:

DFS的回溯算法,如果字符串的分段是回文的就截取片段判断后面的

如果到最后字符串已经被分解的只剩下0的长度,说明就是我们想要的部分,保存到res中

class Solution {
    public List<List<String>> partition(String s){
        List<List<String>> res = new LinkedList<>();
        List<String> path = new ArrayList<>();
        dfs(path,res,s);
        return res;
    }

    private void dfs(List<String> path, List<List<String>> res, String s) {
        if (s.length() == 0){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < s.length(); i++) {
            if (isPalindrome(s,0,i)){
                path.add(s.substring(0,i + 1));
                dfs(path,res,s.substring(i + 1));
                path.remove(path.size() - 1);
            }
        }
    }

    //判断是否回文
    public boolean isPalindrome(String s,int begin,int end){
        while (begin < end){
            if (s.charAt(begin) == s.charAt(end)){
                begin++;
                end--;
            }else {
                return false;
            }
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/zzxisgod/p/13376576.html