题解 | 查找兄弟单词
使用数组代替排序,判断两字符串所含字母是否相同
import java.util.*;
public class Main {
public static void main(String[] args) {
//输入
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = in.next();
}
String target = in.next();
int k = in.nextInt();
//存储兄弟单词
List<String> result = new ArrayList<>();
// 遍历字符串数组 strs
for (String str : strs) {
if (isAnagram(str, target)) {
// 如果是兄弟单词,加入 result
result.add(str);
}
}
//输出
System.out.println(result.size());
if (k <= result.size()) {
Collections.sort(result);
System.out.println(result.get(k - 1));
}
}
/**
* 判断是否为兄弟单词
* @param s1 字符串1
* @param s2 字符串2
* @return 是 true,否 false
*/
private static boolean isAnagram(String s1, String s2) {
// 如果长度不同或完全相同,直接返回 false
if (s1.length() != s2.length() || s1.equals(s2)) {
return false;
}
// 统计每个字母的出现次数
int[] count = new int[26];
// 遍历 s1
for (char c : s1.toCharArray()) {
count[c - 'a']++;
}
// 遍历 s2
for (char c : s2.toCharArray()) {
count[c - 'a']--;
// 如果某字母计数 < 0,说明 s1 中无该字母,返回 false
if (count[c - 'a'] < 0) {
return false;
}
}
return true;
}
}
