题解 | #查找兄弟单词#
查找兄弟单词
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.hasNext()) { // 注意 while 处理多个 case //输入只有一行 String strAll = in.nextLine(); String[] strArr = strAll.split(" "); int n = Integer.parseInt(strArr[0]); //输入的n个字符串 List<String> nStr = new ArrayList<>(); for(int i =0; i< strArr.length; i++) { if(i > 0 && i < strArr.length-2) { nStr.add(strArr[i]); } } //找到输入的 x String x = strArr[(strArr.length-2)]; //找到输入的 k int k = Integer.parseInt(strArr[(strArr.length-1)]); //将x转换成字符数组 char[] xChar = x.toCharArray(); List<String> brothers = new ArrayList<>(); for(String s: nStr) { if(!s.equals(x) && s.length() == x.length()) { char[] sChar = s.toCharArray(); Arrays.sort(xChar); Arrays.sort(sChar); if(Arrays.equals(xChar, sChar)) { brothers.add(s); } } } Collections.sort(brothers); //排序 System.out.println(brothers.size()); // 输入的k要在范围内 if(k>0 && k<=brothers.size()) { System.out.println(brothers.get(k-1)); } } } }