题解 | #查找兄弟单词#

查找兄弟单词

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

import java.util.*;
import java.util.Map.Entry;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static boolean isSibling(String s1, String s2) {
        if (s1.length() != s2.length() || s1.equals(s2)) {
            return false;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            map.merge(s1.charAt(i), 1, (oldVal, newVal) -> oldVal + 1);
            map.merge(s2.charAt(i), -1, (oldVal, newVal) -> oldVal - 1);
        }
        for (Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] arr = new String[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.next();
        }
        String word = sc.next();
        int k = sc.nextInt();
        int ans = 0;
        List<String> list = new ArrayList<>();
        for (String s : arr) {
            if (isSibling(s, word)) {
                list.add(s);
                ans++;
            }
        }
        list.sort(String::compareTo);
        System.out.println(ans);
        if (!list.isEmpty() && k >= 1 && k <= list.size()) {
            System.out.println(list.get(k - 1));
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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