题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.Arrays; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String line = in.nextLine(); print(line); } } private static void print(String line) { String[] arr = line.split("\\s+"); int num = Integer.parseInt(arr[0]); int k = Integer.parseInt(arr[arr.length - 1]); String x = arr[arr.length - 2]; String[] arr1 = Arrays.copyOfRange(arr, 1, 1 + num); Arrays.sort(arr1); int count = 0; String res = ""; for (int i = 0; i < arr1.length; i++) { // 长度一致,并且x中的字母在arr[i]中必须都有,且和x不相等 String s = arr1[i]; String x1 = sortString(x); // 长度相等 字符串本身不相等 排序后的单词和排序后的单词相等 (第K个,给结果赋值 ,其他满足前面三个添加只++ if (s.length() == x.length() && !x.equals(s) && x1.equals(sortString(s)) && ++count == k) { res = s; } } System.out.println(count); if (count > 0) { System.out.println(res); } } private static String sortString(String s) { char[] chars = s.toCharArray(); Arrays.sort(chars); return String.valueOf(chars); } }