题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String input = in.nextLine(); String[] a = input.split(" "); int num = Integer.parseInt(a[0]); String x = a[num + 1]; int count = 0; int k = Integer.parseInt(a[a.length - 1]); List<String> clist = new ArrayList<>(); char[] xchar = x.toCharArray(); for (int i=1;i < 1+num;i++){ Map<Character,Integer> map = new HashMap<>(); for (char n : xchar){ int y =1; if (map.get(n)!= null){ y = map.get(n) + 1; map.put(n,y); } else { map.put(n,y); } } if (a[i].equals(x)){ continue; } if (a[i].length() != x.length()){ continue; } char[] achar = a[i].toCharArray(); for (char j : achar){ int flag = 0; if (map.get(j) != null && map.get(j) !=0){ flag = map.get(j); flag--; map.put(j,flag); } else { break; } } if (map.values().stream().allMatch(integer -> integer==0)) { clist.add(a[i]); count++; } } List<String> mlist = clist.stream().sorted(String::compareTo).collect(Collectors.toList()); if (k < mlist.size()) { System.out.println(count + "\n" + mlist.get(k - 1)); } else { System.out.println(count + "\n"); } } }