题解 | #查找兄弟单词#
查找兄弟单词
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 的区别 int num = in.nextInt(); String[] s = new String[num + 1]; for(int i = 0; i < num; i++){ s[i] = in.next(); } s[num] = in.next(); int k = in.nextInt(); //建立兄弟单词 动态数组 ArrayList<String> arr = new ArrayList<String>(); //对s[num]排序 ArrayList<Character> snumx = new ArrayList<Character>(); for(int i = 0; i < s[num].length(); i++){ snumx.add(s[num].charAt(i)); } Collections.sort(snumx); //遍历添加即可 for(String ss : s){ //字母长度一致 if(ss.length() == s[num].length()){ //不完全相同 if(!ss.equals(s[num])){ //对ss排序 ArrayList<Character> sx = new ArrayList<Character>(); for(int i = 0; i < ss.length(); i++){ sx.add(ss.charAt(i)); } Collections.sort(sx); //比较 if(snumx.equals(sx)){ //相等加入动态数组 arr.add(ss); } } } } Collections.sort(arr); //输出 int res = arr.size();//res个兄弟单词 System.out.println(res); if(res >= k){ System.out.println(arr.get(k-1)); } } }