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

分割回文串。

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路依然是 DFS backtracking。其余思路请直接参考代码。

时间O(n * 2^n) - 一个长度为 n 的字符串,在每个位置都需要尝试分割(递归到下一层),所以复杂度是 2^n。每次分割之后还需要判断回文,再乘以 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         // base case
13         if (s.length() == 0) {
14             res.add(new ArrayList<>(list));
15             return;
16         }
17         for (int i = 0; i < s.length(); i++) {
18             // 如果靠左边的某个子串是回文,才DFS进去看右半边是否也是回文
19             if (isPalindrome(s.substring(0, i + 1))) {
20                 list.add(s.substring(0, i + 1));
21                 helper(res, list, s.substring(i + 1));
22                 list.remove(list.size() - 1);
23             }
24         }
25     }
26 
27     private boolean isPalindrome(String s) {
28         int left = 0;
29         int right = s.length() - 1;
30         while (left < right) {
31             if (s.charAt(left) != s.charAt(right)) {
32                 return false;
33             }
34             left++;
35             right--;
36         }
37         return true;
38     }
39 }

 

LeetCode 题目总结

posted @ 2020-07-09 07:39  CNoodle  阅读(587)  评论(0编辑  收藏  举报