LeetCode 131.分割回文串

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

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

DFS
三个字符的字符串 例如:aab 有四种子串方案 a ab,aa b,a a b, aab 也就是两个数字1,2的所有可能组合 数字代表了对字符串的切割位置
然后就是一个判断子串是否为回文串 这里用一个二维数组去判断从字符串某一个字符开始(行)到某一个字符结束(列)的子串是否为回文串 构造这个二维数组利用了动态规划 即判断一个子串是回文串 它第一个字符和最后一个字符一定相同 并且去掉这两个字符也一定是回文串

class Solution {
    private boolean[][] isPalindrome;
    public List<List<String>> partition(String s) {
        int n = s.length();
        List<List<String>> results = new ArrayList<>();
        List<String> combination = new ArrayList<>();
        getPalindrome(s);
        helper(s, 0, combination, results);
        return results;
    }
    public void getPalindrome(String s){
        int n = s.length();
        isPalindrome = new boolean[n][n];
        for(int i = 0; i < n; i++)
            isPalindrome[i][i] = true;
        for(int i = 0; i < n - 1; i++)
            isPalindrome[i][i+1] = (s.charAt(i) == s.charAt(i+1));
        for(int i = n - 3; i >=0; i--){
            for(int j = i + 2; j < n; j++){
                isPalindrome[i][j] = (isPalindrome[i+1][j-1] && (s.charAt(i) == s.charAt(j)));
            }
        }
    }
    public void helper(String s, int startIndex, List<String> combination, List<List<String>> results){
        if(startIndex == s.length())
            results.add(new ArrayList<>(combination));
        for(int i = startIndex; i < s.length(); i++){
            if(!isPalindrome[startIndex][i])
                continue;
            combination.add(s.substring(startIndex,i + 1));
            helper(s, i + 1, combination, results);
            combination.remove(combination.size() - 1);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值