题解 | #查找兄弟单词#

查找兄弟单词

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

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String[] arr = str.split(" ");
        // 单词个数n
        Integer n = Integer.valueOf(arr[0]);
        // 正整数k
        int k = Integer.parseInt(arr[arr.length - 1]);
        // 单词x
        String x = arr[arr.length - 2];
        int broNo = 0;
        LinkedList<String> broList = new LinkedList<>();
        for (int i = 1; i < arr.length - 2; i++) {
            if (isBro(arr[i], x)) {
                broNo++;
                broList.add(arr[i]);
            }
        }
        System.out.println(broNo);
        if (!broList.isEmpty()) {
            Collections.sort(broList);
            if (broList.size() > k - 1)
                System.out.println(broList.get(k - 1));
        }

    }

    /**
     * 判断给定的str是不是x的兄弟
     *
     * @param str
     * @param x
     * @return
     */
    private static boolean isBro(String str, String x) {
        // 长度不一样肯定不是
        if (x.length() != str.length()) {
            return false;
        }
        // 单词一样也不是
        if (x.equals(str)) {
            return false;
        }
        int len = x.length();
        LinkedList<String> strList = new LinkedList<>();
        LinkedList<String> xList = new LinkedList<>();
        // 长度一样,单词里面的字母都一样就算是兄弟单词
        for (int i = 0; i < len; i++) {
            strList.add(str.charAt(i) + "");
            xList.add(x.charAt(i) + "");
        }
        // 分别将2个字符串的字母放到2个有序的List里面并排序一下
        Collections.sort(strList);
        Collections.sort(xList);
        // 挨个拿出来对比,如果不一样就返回false
        for (int i = 0; i < len; i++) {
            if (!strList.pop().equals(xList.pop())) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务