Thursday, March 14, 2013

[LeetCode] Palindrome Partitioning

Thought:
Classical BFS.
The format of BFS is just like this.
The end condition + the forward method.

Code:
public class Solution {
    private static ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
    private static ArrayList<String> cache = new ArrayList<String>();
   
    private boolean isPalindrome(String s, int start, int end) {
        int i = start;
        int j = end;
        while (i < j) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }
    public ArrayList<ArrayList<String>> partition(String s) {
        result.clear();
        cache.clear();
        dfs(s, 0);
        return result;
    }
    public void dfs(String s, int depth) {
        if (depth == s.length()) result.add(new ArrayList<String>(cache));
        for (int end = depth; end < s.length(); end++) {
            if (isPalindrome(s, depth, end)) {
                cache.add(s.substring(depth, end + 1));
                dfs(s, end + 1);
                cache.remove(cache.size() - 1);
            }
        }
    }   
}

No comments:

Post a Comment