LeetCode 131 Palindrome Partitioning

LeetCode 131 Palindrome Partitioning

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"]]

和combination,permutation類似可以使用backtracing或dp,對于這類題backtracing的方法比較熟,所以直接回溯實現了。
submit了三遍才AC,發現是isPalindrome里有一個小錯誤。。。

代碼:

public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<List<String>>();
        if (s.length() == 0) return res;
        partitionRecursive(s, 0, new ArrayList<String>(), res);
        return res;
    }
    
    public boolean isPalindrome(String str) {
        int st = 0, ed = str.length()-1;
        while (st < ed) {
            if (str.charAt(st) != str.charAt(ed)) return false;
            st++;
            ed--;
        }
        return true;
    }
    
    public void partitionRecursive(String s, int index, List<String> p, List<List<String>> res) {
        if (index == s.length()) {
            res.add(new ArrayList(p));
            return;
        }
        
        for (int i = index+1; i <= s.length(); i++) {
            String str = s.substring(index, i);
            if (isPalindrome(str)) {
                p.add(str);
                partitionRecursive(s, i, p, res);
                p.remove(p.size()-1);
            }
        }
    }
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容