All possibilities of DFS-string cutting (the elements in the combined result must all be palindrome strings)

Title: Given "abc", all possible segmentation combinations are given, and all elements in the combination must be palindrome strings.
example1: [a, b, c], [a, bc], [ab, c], [abc], the result is only [a, b, c] is a palindrome example2: give aab: all cut
combinations Form [a,a,b], [aa,b], [a,ab], [aab], only [a,a,b], [aa,b] are palindrome strings

/**
 * 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;
    }
}

Guess you like

Origin blog.csdn.net/tmax52HZ/article/details/130117170