131. Palindrome Partitioning -Medium

Question

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

给出一个字符串s,将s分割为回文字串,返回所有的分割方法

Example

given s = “aab”,

Return:
[
[“aa”,”b”],
[“a”,”a”,”b”]
]

Solution

  • 回溯解。每次对以当前字符开头的字符串进行判断是否是回文字符串,如果是则判断之后的字符串,否则跳过。比如”aab”,首先判断以a开头的字符串是否是回文字符串,”a”,”aa”,”aab”,而其中”a”和”aa”是回文字符串,所以分别按同样的方法继续哦判断”ab”,”b”。

    public class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> res = new ArrayList<>();
            backtracking(s, 0, res, new ArrayList<>());
            return res;
        }
    
        /**
         * 思路:每次对以当前开始索引开头的字符串进行判断是否是回文字符串,
         *      如果是则判断接下去的字符串,否则跳过。
         * @param s:需要分割的字符串
         * @param start:字符串开头索引
         * @param res:保存分割结果
         * @param temp:保存当前组合结果
         */
        public void backtracking(String s, int start, List<List<String>> res, List<String> temp){
            // 如果已经分割完字符串则添加到结果集
            // 因为单个字符串也算回文字符串,所以不会出现分割完却有某个字符串不是回文的情况
            if(start == s.length()){
                res.add(new ArrayList<>(temp));
            }
            // 判断以s[i]字符开头的字符串是否有回文字符串
            for(int i = start; i < s.length();i++){
                // 如果是回文则继续判断该回文字符串后面的字符串
                if(isPalindrome(s, start, i)){
                    temp.add(s.substring(start, i + 1));
                    backtracking(s, i + 1, res, temp);
                    temp.remove(temp.size() - 1);
                }
            }
        }
    
        /**
         * 思路:判断字符串s[l:r]是否为回文字符串
         * @param s:字符串
         * @param l:字符串开头索引
         * @param r:字符串结尾索引
         * @return:是否为字符串,是则True,否则False
         */
        public boolean isPalindrome(String s, int l, int r){
            if(l > r) return true;
            if(s.charAt(l) != s.charAt(r)) return false;
            return isPalindrome(s, l + 1, r - 1);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值