131. Palindrome Partitioning

Link

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

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]

Solution

此題要考慮所有可能性,最直覺的想法就是暴力計算,透過back tracking

choose: 每個(0...i)子字串若回文,則choose observe: 重複(i....n) 子字串的判定 unchoose: undo choose 何時tempResult可以更新到finalResult? 應該是remained subString已經沒東西了,代表之前的subString都已經是回文的狀態,已經加入tempResult。

  public static List<List<String>> partition(String s) {
        // Backtracking
        // Edge case
        if (s == null || s.length() == 0) return new ArrayList<>();

        List<List<String>> result = new ArrayList<>();
        helper(s, new ArrayList<>(), result);
        return result;
    }

    public static void helper(String s, List<String> step, List<List<String>> result) {
        // Base case
        if (s.length() == 0) {
            result.add(new ArrayList<>(step));
            return;
        }
        for (int i = 1; i <= s.length(); i++) {
            String temp = s.substring(0, i);
            if (!isPalindrome(temp)) continue; // only do backtracking when current string is palindrome

            step.add(temp);  // choose
            helper(s.substring(i), step, result); // explore
            step.remove(step.size()-1); // unchoose
        }
        return;
    }

    public static boolean isPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        while (left <= right) {
            if (s.charAt(left) != s.charAt(right))
                return false;
            left++;
            right--;
        }
        return true;
    }

Last updated

Was this helpful?