[Leetcode] Palindrome Partitioning

来源:互联网 发布:三星s4可以用4g网络吗 编辑:程序博客网 时间:2024/04/30 08:18

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 {    public List<List<String>> partition(String s) {        List<String> cur = new ArrayList<>();        List<List<String>> result = new ArrayList<>();        partition(s.toCharArray(), 0, cur, result);        return result;    }        private void partition(char[] s, int start, List<String> cur, List<List<String>> result) {        if(start == s.length) {            result.add(new ArrayList<>(cur));            return;        }        StringBuilder str = new StringBuilder();        for(int i = start; i < s.length; i++) {            str.append(s[i]);            if(isPalindrome(str)){                cur.add(str.toString());                partition(s, i+1, cur, result);                cur.remove(cur.size() - 1);            }        }        return;    }        private boolean isPalindrome(StringBuilder str) {        int start = 0;        int end = str.length() - 1;        while(start <= end) {            if(str.charAt(start) != str.charAt(end)) {                return false;            }            start++;            end--;        }        return true;    }}


0 0
原创粉丝点击