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

题目:给出"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;
    }
}

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/130117170