题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); String[] ss = new String[num]; for (int i = 0; i < num; i++) { ss[i] = in.next(); } String word = in.next(); int key = in.nextInt(); List<String> list = new ArrayList(); for (int i = 0; i < num; i++) { if (isBrother(word, ss[i])) { list.add(ss[i]); } } System.out.println(list.size()); String[] result = list.toArray(new String[list.size()]); Arrays.sort(result); for (int i = 0; i < result.length; i++) { if (i == key-1) { System.out.println(result[i]); } } } public static boolean isBrother(String word, String s) { if (word.length()!=s.length()||word.equals(s)) { return false; } char[] w = word.toCharArray(); Arrays.sort(w); char[] ss = s.toCharArray(); Arrays.sort(ss); return String.valueOf(w).equals(String.valueOf(ss)); } }
知识点:
List<String> list = new ArrayList();
String[] result = list.toArray(new String[list.size()]);
Arrays.sort(result);
这里不能用treeset、虽然其是有序的但是不重复。