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

A palindrome string is a string that reads the same backward as forward.

Example 1:

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

Example 2:

Input: s = "a"
Output: [["a"]]

Constraints:

  • 1 <= s.length <= 16
  • s contains only lowercase English letters.

分割回文串。

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

思路依然是回溯backtracking。

时间O(2^n)

空间O(n)

Java实现

 1 class Solution {
 2     public List<List<String>> partition(String s) {
 3         List<List<String>> 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<List<String>> res, List<String> 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 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13270369.html