[leetCode 131]Palindrome Partitioning

来源:互联网 发布:知乎 唯一视觉怎么样 编辑:程序博客网 时间:2024/05/01 20:04

题目:
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”]
]
自然而然的思路:
递归回溯

public class Solution {   List<List<String>> result = new ArrayList<>();    List<String> path = new ArrayList<>();    public List<List<String>> partition(String s) {        helper(s);        return result;    }    void helper(String s)    {        if(s.length() == 0)        {            List<String> r = new ArrayList<>(path);            result.add(r);        }        for(int i = 0;i<s.length();i++)        {            String str = s.substring(0,i+1);            if(isPoalindrome(str))            {                path.add(str);                helper(s.substring(i+1));                path.remove(path.size()-1);            }        }    }    boolean isPoalindrome(String s)    {        int i = 0,j = s.length()-1;        while(i<=j)        {            if(s.charAt(i) != s.charAt(j)){return false;}            i++;            j--;        }        return true;    }}
1 0