LeetCode 131.分割回文串

题目地址:LeetCode 131.分割回文串

1.问题思路

知题意,将字符串分割成若干个回文串。其实分割问题差不多就是组合问题,依然可以使用回溯思想。面对回溯算法通常使用DFS查找,依据递归三部曲:

  1. 递归方法参数及返回值
    需要得到可能结果一般为void。由于需要对已经分割的子串进行再次分割,直到分割位置到达字符串尾部终止终止,所以还需要startIndex记录分割位置。
  2. 终止条件
    即startIndex=s.length-1时退出
  3. 本层遍历区间及处理
    遍历区间为[startIndex, s.length-1],如当前[i, startIndex]为回文串则需要进行下层遍历dfs(s, startIndex+1),如当前不为回文串则进行剪枝。

2.代码实现

    class Solution {
        List<List<String>> list = new ArrayList<>();
        List<String> path = new ArrayList<>();
        
        public List<List<String>> partition(String s) {
            dfs(s, 0);
            return list;
        }

        /**
         * 查找分割子串
         *    如果当前分割的字符串不是回文串,则返回
         *              ··· 是回文串, 则从startIndex+1再次切割
         * @paam s
         * @param startIndex
         */
        public void dfs(String s, int startIndex) {
            // startIndex超过了s的最大长度,则代表当前分割的字符串全是回文串
            if (startIndex >= s.length()) {
                list.add(new ArrayList<>(path));
                return;
            }
			
			// 对当前进行切割
            for (int i = startIndex; i < s.length(); i++) {
                if (isPalindrome(s, startIndex, i)) {
                    path.add(s.substring(startIndex, i+1));
                } else {
                    // 剪枝!!! 如果当前为回文串, 则跳过
                    continue;
                }
				// 回溯
                dfs(s, i + 1);
                path.remove(path.size()-1);
            }

        }

        /**
         * 双指针思路
         * 判断字符串是否是回文字符串
         * @param s
         * @return
         */
        public boolean isPalindrome(String s, int startIndex, int endIndex) {
            boolean result = true;
            while (startIndex < endIndex) {
                if (s.charAt(startIndex) == s.charAt(endIndex)) {
                    startIndex++;
                    endIndex--;
                } else {
                    result = false;
                    break;
                }
            }

            return result;
        }
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值