题解 | #查找兄弟单词#

查找兄弟单词

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

模拟

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);

        String[] split = br.readLine().split(" ");
        int n = Integer.parseInt(split[0]);
        String[] dictionary = new String[n];
        for (int i = 1; i <= n; i++) {
            dictionary[i - 1] = split[i];
        }
        String pattern = split[n + 1];
        int k = Integer.parseInt(split[n + 2]);

        List<String> brothers = new ArrayList<>();
        for (String word : dictionary) {
            if (isBrother(word, pattern)) {
                brothers.add(word);
            }
        }
        Collections.sort(brothers);
        pw.println(brothers.size());
        if (k - 1 < brothers.size()) {
            pw.println(brothers.get(k - 1));
        }

        pw.flush();
        pw.close();
        br.close();
    }

    private static boolean isBrother(String word, String pattern) {
        if (word.length() != pattern.length() || word.equals(pattern)) {
            return false;
        }
        int[] count = new int[26];
        for (char c : word.toCharArray()) {
            count[c - 'a']++;
        }
        for (char c : pattern.toCharArray()) {
            count[c - 'a']--;
        }
        for (int i = 0; i < 26; i++) {
            if (count[i] != 0) {
                return false;
            }
        }
        return true;
    }
}
全部评论

相关推荐

10-31 14:54
已编辑
门头沟学院 算法工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务