3 abc bca cab abc 1输出:
2 bca
6 cab ad abcd cba abc bca abc 1输出:
3 bca说明:
abc的兄弟单词有cab cba bca,所以输出3 经字典序排列后,变为bca cab cba,所以第1个字典序兄弟单词为bca
1 import java.util.*; 2 3 public class Main { 4 public static void main(String[] args) { 5 6 Scanner scanner = new Scanner(System.in); 7 8 while (scanner.hasNext()){ 9 //输入拆分为字符串数组 10 String[] s1 = scanner.nextLine().split(" "); 11 //多少个字符串 12 int n = Integer.parseInt(s1[0]); 13 //第x位置的字符串 14 String x = s1[s1.length -2]; 15 int k = Integer.parseInt(s1[s1.length-1]); 16 17 //创建字符串list,判断单词是否兄弟单词,是则添加到list中 18 List<String> ls = new ArrayList<>(); 19 for(int i=1; i<=n; i++) { 20 if(isBrother(x,s1[i])){ 21 ls.add(s1[i]); 22 } 23 } 24 System.out.println(ls.size()); //输出兄弟单词个数 25 26 Collections.sort(ls); //字母排序 27 if(ls.size() >= k) { 28 System.out.println(ls.get(k - 1)); 29 } 30 } 31 } 32 33 //将x和要比较的单词拆分为字符重新排序后比较 34 public static boolean isBrother(String x, String s) { 35 if(x.length() != s.length() || s.equals(x)) { 36 return false; 37 } 38 char[] cx = x.toCharArray(); 39 char[] cs = s.toCharArray(); 40 41 Arrays.sort(cx); 42 Arrays.sort(cs); 43 // boolean res = String.valueOf(cx).equals(String.valueOf(cs)); 44 boolean res = new String(cx).equals(new String(cs)); //String构造方法转换 45 return res; 46 } 47 }