LeetCode 131. Palindrome Partitioning

来源:互联网 发布:严格模式js有什么好处 编辑:程序博客网 时间:2024/05/29 18:40

description:
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<List<String>> result = new ArrayList<>();        if (s == null || s.length() == 0) {            return result;        }        List<String> arr = new ArrayList<>();        util(result, arr, s,0);        return result;    }    private void util(List<List<String>> result,                                    List<String> arr,                                    String s,                                    int start){        if (start == s.length()) {            result.add(new ArrayList<>(arr));            return;        }        for (int i = start; i < s.length(); i++) {            String substr = s.substring(start, i + 1);            if (isPalindrome(substr)) {                arr.add(substr);                util(result, arr, s, i + 1);                arr.remove(arr.size() - 1);            }        }    }    private boolean isPalindrome(String str) {        if (str.length() == 0) {            return true;        }        int left = 0;        int right = str.length() - 1;        while (left <= right) {            if(str.charAt(left++) != str.charAt(right--)) {                return false;            }        }        return true;    }}
0 0
原创粉丝点击