题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); while (sc.hasNext()) { String[] str = new String[n]; for (int i = 0 ; i < n; i++) { str[i] = sc.next(); } String demo = sc.next(); int index = sc.nextInt(); Map<Character, Integer> map = new HashMap<>(); //统计样本单词每个字母的数量 for (char ch : demo.toCharArray()) { map.put(ch, map.getOrDefault(ch, 0) + 1); } List<String> resList = new ArrayList<>(); for (String s : str) { if (s.equals(demo)) { continue; } Map<Character, Integer> mapDeep = new HashMap<>(); mapDeep.putAll(map); for (char ch2 : s.toCharArray()) { if (mapDeep.containsKey(ch2)) { //减小map中被用过单词的数量 mapDeep.put(ch2, mapDeep.get(ch2) - 1); } else { mapDeep.put(ch2, -1); } } Collection<Integer> values = mapDeep.values(); if (Collections.min(values) == 0 && Collections.max(values) == 0) { resList.add(s); } } System.out.println(resList.size()); Collections.sort(resList); if(index > resList.size()){ System.out.println(); }else{ System.out.println(resList.get(index - 1)); } } } }