Leetcode 131. Palindrome Partitioning

题目链接:https://leetcode.cn/problems/palindrome-partitioning/

方法一 回溯+ 判断回文串函数

1 方法思想

2 代码实现

class Solution {
    List<List<String>> result = new ArrayList<>();
    LinkedList<String> subString = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backTraking(s, 0);
        return result;
    }

    public void backTraking(String s, int start) {
        
        if (start >= s.length()){
            result.add(new ArrayList<>(subString));
            return;
        }
        
        for (int i = start; i < s.length(); i++) {
            if (isPalindrome(s, start, i)){
                subString.add(s.substring(start, i + 1));
                backTraking(s, i + 1);
                subString.removeLast();
            }
        }

    }
    
    public boolean isPalindrome(String str, int start, int end) {
        while (start < end) {
            if (str.charAt(start++) != str.charAt(end--)) {
                return false;
            }
        }
        return true;
    }
}

3 复杂度分析

时间复杂度:
空间复杂度:

4 涉及到知识点

5 总结

方法二 回溯+回文串预判断数组

1 方法思想

2 代码实现

public class Solution {

    List<List<String>> result = new ArrayList<>();
    LinkedList<String> subString = new LinkedList<>();

    public List<List<String>> partition(String s) {
        int len = s.length();
        boolean[][] isPalindrome = new boolean[len][len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j <= i; j++) {
                if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || isPalindrome[j + 1][i - 1])) {
                    isPalindrome[j][i] = true;
                }
            }
        }
        
        backTraking(s, 0, isPalindrome);
        return result;
    }

    public void backTraking(String s, int start, boolean[][] isPalindrome) {

        if (start == s.length()) {
            result.add(new ArrayList<>(subString));
            return;
        }

        for (int i = start; i < s.length(); i++) {
            if (isPalindrome[start][i]) {
                subString.add(s.substring(start, i + 1));
                backTraking(s, i + 1, isPalindrome);
                subString.removeLast();
            }
        }

    }
}


3 复杂度分析

时间复杂度:
空间复杂度:

4 涉及到知识点

5 总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值