题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.Comparator; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); String[] strs = new String[count]; for(int i = 0; i < count; ++i){ strs[i] = sc.next(); } String compare = sc.next(); int k = sc.nextInt(); ArrayList<String> result = new ArrayList<>(); for (String str : strs) { if(isAnagram(compare, str)){ result.add(str); } } // 字符串排序算法 result.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { char[] o1s = o1.toCharArray(); char[] o2s = o2.toCharArray(); for(int i = 0; i < o1s.length && i < o2s.length; ++i){ if(o1s[i] < o2s[i]){ return -1; } if(o1s[i] > o2s[i]){ return 1; } } if(o1s.length <= o2s.length){ return -1; } else { return 1; } } }); System.out.println(result.size()); if(k < result.size()){ System.out.println(result.get(k - 1)); } } // 判断是否是有效的“兄弟单词”(即:变位词) private static boolean isAnagram(String compare, String str) { if(compare == null || str == null || compare.length() != str.length() || compare.equals(str)){ return false; } int[] alphabet = new int[26]; for (char c : compare.toCharArray()) { alphabet[c - 'a']++; } for (char c : str.toCharArray()) { if(alphabet[c - 'a'] == 0){ return false; } alphabet[c - 'a']--; } return true; } }