题解 | #查找兄弟单词#

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] split = scanner.nextLine().split(" ");
        String target = split[split.length-2];
        List<String> curList = new ArrayList<>(Arrays.asList(split).subList(1, split.length - 2));
        List<String> targetList = new ArrayList<>();
        dfs(new StringBuilder(),target.toCharArray(),new boolean[target.length()],targetList);
        int count = 0, k = Integer.parseInt(split[split.length-1]);
        List<String> resList = new ArrayList<>();
        for (String str : curList) {
            if (!str.equals(target) && targetList.contains(str)){
                count++;
                resList.add(str);
            }
        }
        resList.sort(String::compareTo);
        System.out.println(count);
        if (resList.size() > k)System.out.println(resList.get(k - 1));
    }

    private static void dfs(StringBuilder builder, char[] chars, boolean[] booleans
                            , List<String> targetList) {
        if (builder.length() == chars.length) {
            targetList.add(builder.toString());
            return;
        }
        for (int i = 0; i < chars.length; i++) {
            if (!booleans[i]) {
                builder.append(chars[i]);
                booleans[i] = true;
                dfs(builder, chars, booleans, targetList);
                booleans[i] = false;
                builder.deleteCharAt(builder.length() - 1);
            }
        }

    }
}

全部评论

相关推荐

11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务