题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*; import java.util.stream.Stream; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("\n"); while (scanner.hasNext()) { String next = scanner.next(); String[] S = next.split(" "); int num = Integer.parseInt(S[0]); int k = Integer.parseInt(S[S.length-1]); String target = S[S.length-2]; ArrayList<String> arrayList = new ArrayList<>(); for (int i = 1; i < S.length-2; i++) { if (S[i].length() != target.length() || target.equals(S[i])) { continue; } if (is(target, S[i])) { arrayList.add(S[i]); } } System.out.println(arrayList.size()); Stream<String> sorted = arrayList.stream().sorted(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); Object[] objects = sorted.toArray(); System.out.println(k<=arrayList.size()?objects[k-1]:""); } } public static boolean is(String S1, String S2) { char[] chars1 = S1.toCharArray(); for (int i = 0; i < chars1.length; i++) { if (S2.contains(chars1[i] + "")) { S2 = S2.replaceFirst(chars1[i] + "", ""); } else { return false; } } return true; } }