题解 | #查找兄弟单词#

查找兄弟单词

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    private static List<String> brothers = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            String[] dics = new String[n];
            for (int i = 0; i < n; i++) {
                dics[i] = in.next();
            }
            String word = in.next();
            int index = in.nextInt();
            char[] chars = word.toCharArray();
            // 1 输出可能的兄弟单词,在已提供的字典单词中筛选兄弟单词
            // 1.1 求解单词的可能的兄弟单词:解析出各个字母(含重复字母),按字典序排列组合
            solution(chars, 0);
            brothers.remove(word);
            
            int count = 0;
            List<String> targets = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                if (brothers.contains(dics[i])) {
                    count++;
                    targets.add(dics[i]);
                }
            }
            System.out.println(count);
            // 3 按字典序列输出index的兄弟单词
            String[] targetsInOrder = targets.toArray(new String[]{});
            Arrays.sort(targetsInOrder);
            if (index <= targetsInOrder.length) {
                System.out.println(targetsInOrder[index - 1]);
            } 
        }
    }

    public static void solution(char[] chars, int begin) {
        if (begin >= chars.length) {
            return;
        }
        if (begin == chars.length - 1) {
            brothers.add(String.valueOf(chars));
            return;
        }
        for (int j = begin; j < chars.length; j++) {
            if (checkIfCanSwap(chars, begin, j)) {
                swap(chars, begin, j);
                solution(chars, begin + 1);
                swap(chars, begin, j);
            }
        }
    }

    public static boolean checkIfCanSwap(char[] chars, int begin, int end) {
        for (int i = begin; i < end; i++) {
            if (chars[begin] == chars[end]) {
                return false;
            }
        }
        return true;
    }

    public static void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }

}

全部评论

相关推荐

明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
Aki-Tomoya:窝趣,人家这是先富带动后富,共同富裕了属于是
投递英伟达等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务