题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 // while (in.hasNextInt()) { // 注意 while 处理多个 case // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } // 思路:先查找到单词的兄弟单词,然后进行排序,比较是否是兄弟单词的时候,不仅要比较是否包含截取出来的字符,而且需要数量相同。 // 先收集输入 String str = in.nextLine(); String[] strArr = str.split(" "); // 初始化两个HashMap用来存放单词进行比较 TreeMap<Character,Integer> temp1 = new TreeMap<>(); TreeMap<Character,Integer> temp2 = new TreeMap<>(); for (char s : strArr[strArr.length -2].toCharArray()) { temp2.put(s,temp2.getOrDefault(s,1)+1); } // 初始化一个数组用来存放兄弟单词 ArrayList<String> temp3 = new ArrayList<>(); for (int i = 1; i < strArr.length - 1 ; i++) { if (!strArr[i].equals(strArr[strArr.length - 2])) { for (char s : strArr[i].toCharArray()) { temp1.put(s,temp1.getOrDefault(s,1)+1); } if (temp2.equals(temp1)) { temp3.add(strArr[i]); } temp1.clear(); } } // 对temp3进行排序 Collections.sort(temp3); System.out.println(temp3.size()); if (Integer.valueOf(strArr[strArr.length - 1]) < temp3.size()) { System.out.print(temp3.get(Integer.valueOf(strArr[strArr.length - 1]) - 1)); } } }