zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    算法-转
    单页 SEO-转
    浅谈MVVM设计模式
    iOS-UIView动画
    iOS 核心动画(下)
    iOS开发-核心动画(Core Animation)
    iOS-CALayer的介绍
    SVN Xcode不能提交.a文件
    iOS 毛玻璃效果
    Quartz2D学习总结
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13260104.html
Copyright © 2011-2022 走看看