DFS-字符串切割的所有可能(要求组合结果中的元素必须都为回文串)

该代码示例是一个Java程序,用于找到给定字符串的所有可能切割组合,条件是每个组合元素必须是回文串。它使用深度优先搜索(DFS)策略,通过递归遍历字符串的每个子串,并检查是否为回文。如果满足条件,将子串添加到结果列表中。
摘要由CSDN通过智能技术生成

题目:给出"abc",给出所有可能的切分组合,要求组合中所有元素必须为回文串。
example1:[a, b, c]、[a,bc]、[ab,c]、[abc],结果只有[a, b, c]为回文串
example2:给出aab : 所有切割后的组合形式[a,a,b]、[aa,b]、[a,ab]、[aab],结果只有[a,a,b]、[aa,b]为回文串

/**
 * Author:m
 * Date: 2023/04/11 22:51
 */
public class SplitAbcResultPalindrome {
    public static void main(String[] args) {
        String candidate = "aac";
        List<List<String>> res = dfs(candidate);
        System.out.println(res);
    }

    private static List<List<String>> dfs(String candidate) {
        List<List<String>> result = Lists.newArrayList();
        if (StringUtils.isBlank(candidate)) {
            return result;
        }

        List<String> combine = Lists.newArrayList();
        int startIndex = 0;
        recursion(result, combine, candidate, startIndex);
        return result;
    }

    private static void recursion(List<List<String>> result, List<String> combine, String candidate, int startIndex) {
        // 1.终止条件
        // 2.小集合添加至大集合
        if (startIndex == candidate.length()) {
            result.add(Lists.newArrayList(combine));
        }

        // 3.循环
        for (int i = startIndex; i < candidate.length(); i++) {
            String subStr = candidate.substring(startIndex, i + 1);
            // 3.1 去重|过滤(这里要求元素必须为回文串)
            if (!strIsPalindrome(subStr)) {
                continue;
            }
            // 3.2优化
            // 3.3添加元素至小集合
            combine.add(subStr);
            // 3.4递归(i+1)
            recursion(result, combine, candidate, i + 1);
            // 3.5回溯(删除小集合中最后一个元素)
            combine.remove(combine.size() - 1);
        }
    }

    private static boolean strIsPalindrome(String str) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        if (str.length() == 1) {
            return true;
        }
        char[] chars = str.toCharArray();
        for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
            if (chars[i] != chars[j]) {
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值