分割回文串 · Palindrome Partitioning

[抄题]:

给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。

返回s所有可能的回文串分割方案。

给出 s = "aab",返回

[
  ["aa", "b"],
  ["a", "a", "b"]
]

[思维问题]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 主函数中要记得新建partition数组
  2. 字符串取长度需要加括号.length()
  3. j的起始位置是length - 1 保证有数,最后的结束条件是i < j,二者相邻
  4. 回溯法反复递归调用的是helper函数下一组进行操作, remove的是partition.size() - 1

[二刷]:

  1. List<List<String>>也必须用arraylist来实现
  2. 取子数组的方法是.substring()简称sb
  3. 要检验新数组是否有效,若不是回文字符串则退出

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

valid函数变成了回文串判断函数

[复杂度]:Time complexity: O(宽度的深度次方) Space complexity: O(宽度*深度)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

DFS,找出所有方法

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

分割回文串 II · Palindrome Partitioning II -DP

 [代码风格] :

public class Solution {
    /*
     * @param s: A string
     * @return: A list of lists of string
     */
    public List<List<String>> partition(String s) {
        //corner case
        List<List<String>> result = new ArrayList<>();
        List<String> partition = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return result;
        }
        helper(s, partition, 0, result);
        return result;
    }
    //helper
    private void helper (String s, List<String> partition,
    int startIndex, List<List<String>> result) {
        if (startIndex == s.length()) {
            result.add(new ArrayList<String>(partition));
            return ;
        }
        
        for (int i = startIndex; i < s.length(); i++) {
            String sb = s.substring(startIndex, i + 1);
            if (!isPalindrome(sb)) {
                continue;
            }
            partition.add(sb);
            helper(s, partition, i + 1, result);
            partition.remove(partition.size() - 1);
        }
    }
    //isPalindrome
    private boolean isPalindrome (String s) {
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8413774.html