[LeetCode] 131. Palindrome Partitioning

Problem

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

1
2
3
4
5
6
Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

Explanation

  1. First create a function to check whether a string is palindrome.
  2. We can use backtracking to find all combination, if a substring is palindrome, then we start from the next character of the substring and check. For example, “abac”, when we check “aba” is a palindrome, then we check start from “c”.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
    boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start += 1;
            end -= 1;
        }

        return true;
    }

    void helper(String s, int start, List<String> out, List<List<String>> res) {
        if (start == s.length()) {
            res.add(new ArrayList<>(out));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (isPalindrome(s, start, i)) {
                out.add(s.substring(start, i+1));
                helper(s, i+1, out, res);
                out.remove(out.size()-1);
            }
        }
    }

    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<List<String>>();
        List<String> out = new ArrayList<>();
        helper(s, 0, out, res);
        return res;
    }
}