Middle-题目78:131. Palindrome Partitioning

原创 2016年05月31日 16:57:34

题目原文:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = “aab”,
Return
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
题目大意:
返回字符串s的所有回文子串的分割。
题目分析:
使用backtrack(List<List<String>> list, List<String> sublist, String s)维护搜索过程,每次从s的开头开始截取字符串,每次判断一下是否为回文串,如果是就放入sublist,然后去掉加入sublist的部分继续向下搜索,直到s为空。
源码:(language:java)

public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> list = new ArrayList<List<String>>();
        backtrack(list,new ArrayList<>(),s);
        return list;
    }
    private void backtrack(List<List<String>> list, List<String> sublist, String s) {
        if(s.length() == 0) {
            list.add(new ArrayList<String>(sublist));
        }       
        else {
            for(int i = 1; i<=s.length();i++) {
                if(isPalindrome(s.substring(0, i))) {
                    sublist.add(s.substring(0, i));
                    backtrack(list, sublist, s.substring(i));
                    sublist.remove(sublist.size()-1);
                }
            }
        }
    }
    public boolean isPalindrome(String s) {
        if(s==null||s.length()==0)
            return true;

        for(int i = 0,j = s.length()-1;i<j;i++,j--) {
            if(s.charAt(i)!=s.charAt(j))
                return false;
        }
        return true;
    }
}

成绩:
8ms,beats 31.90%,众数8ms,29.29%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode 131. Palindrome Partitioning 树形问题,状态回溯

131. Palindrome Partitioning Given a string s, partition s such that every substring of the partit...

LeetCode: Palindrome Partitioning [131]

【题目】 Given a string s, partition s such that every substring of the partition is a palindrome. Ret...

【leetcode】131. Palindrome Partitioning

【leetcode】131. Palindrome Partitioning

Python中的浅复制与深复制9(解LeetCode Palindrome Partitioning)

.

【Leetcode】131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome. Return al...

LeetCode 46. Permutations47. Permutations II&&131. Palindrome Partitioning(全排列问题)

LeetCode 46. Permutations Given a collection of distinct numbers, return all possible permutations...

131. Palindrome Partitioning -Medium

Question Given a string s, partition s such that every substring of the partition is a palindrome....

Leetcode 131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.Return all ...

leetcode 131. Palindrome Partitioning-回溯算法

原题链接:131. Palindrome Partitioning 【思路-Java】递归实现 本题采用回溯算法实现。 1. 最外层循环 public class Solution { pub...

Leetcode 131 Palindrome Partitioning 回文分割

给出一个字符串s,对s进行分割,使得每一个子串都是一个回文串,返回s所有可能的回文分割...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目78:131. Palindrome Partitioning
举报原因:
原因补充:

(最多只允许输入30个字)