131. 分割回文串

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

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

示例:

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


链接:https://leetcode-cn.com/problems/palindrome-partitioning

py

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res=[]
        def helper(s,tmp):
            if not s:
                res.append(tmp)#空字符说明处理完毕
            for i in range(1,len(s)+1):
                if s[:i]==s[:i][::-1]:#判断回文
                    helper(s[i:],tmp+[s[:i]])#回溯
        
        helper(s,[])
        return res

 

 Java

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> list = new ArrayList<>();
        backtrack(list, new ArrayList<>(), s, 0);
        return list;
    }

    public void backtrack(List<List<String>> list, List<String> tempList, String s, int start){
        if(start == s.length())
            list.add(new ArrayList<>(tempList));
        else{
            for(int i = start; i < s.length(); i++){
                if(isPalindrome(s, start, i)){
                    tempList.add(s.substring(start, i + 1));
                    backtrack(list, tempList, s, i + 1);
                    tempList.remove(tempList.size() - 1);
                }
            }
        }
    }

    public boolean isPalindrome(String s, int low, int high){
        while(low < high)
            if(s.charAt(low++) != s.charAt(high--)) return false;
        return true;
    }
}

 

posted @ 2020-07-07 12:37  XXXSANS  阅读(166)  评论(0编辑  收藏  举报