[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.

Example:

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

分割回文串。题意是给一个字符串,请做适当分割,使得分割的子串都是回文串。

思路依然是回溯backtracking。

时间O(2^n)

空间O(n)

Java实现

 1 class Solution {
 2     public List> partition(String s) {
 3         List> res = new ArrayList<>();
 4         if (s == null || s.length() == 0) {
 5             return res;
 6         }
 7         helper(res, new ArrayList<>(), s);
 8         return res;
 9     }
10 
11     private void helper(List> res, List list, String s) {
12         if (s.length() == 0) {
13             res.add(new ArrayList<>(list));
14             return;
15         }
16         for (int i = 0; i < s.length(); i++) {
17             if (isPalindrome(s.substring(0, i + 1))) {
18                 list.add(s.substring(0, i + 1));
19                 helper(res, list, s.substring(i + 1));
20                 list.remove(list.size() - 1);
21             }
22         }
23     }
24 
25     private boolean isPalindrome(String s) {
26         for (int i = 0; i < s.length() / 2; i++) {
27             if (s.charAt(i) != s.charAt(s.length() - i - 1)) {
28                 return false;
29             }
30         }
31         return true;
32     }
33 }

 

LeetCode 题目总结

你可能感兴趣的:([LeetCode] 131. Palindrome Partitioning)