题解 | #查找兄弟单词#
查找兄弟单词
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);
int n = in.nextInt();
String[] dict = new String[n];
for (int i = 0; i < n; i++) {
dict[i] = in.next();
}
String keyWord = in.next();
List<SuperString> matchList = new ArrayList<>();
int k = in.nextInt();
SuperString superKeyWord = new SuperString(keyWord);
for (String s : dict) {
SuperString superString = new SuperString(s);
if (superKeyWord.match(superString)) {
matchList.add(superString);
}
}
matchList.sort((a, b) -> a.raw.compareTo(b.raw));
System.out.println(matchList.size());
if (matchList.size() >= k) {
System.out.println(matchList.get(k - 1).raw);
}
}
static class SuperString {
String raw;
String featureStr;
SuperString(String raw) {
this.raw = raw;
char[] chars = raw.toCharArray();
Arrays.sort(chars);
StringBuilder builder = new StringBuilder();
builder.append(chars[0]);
int count = 1;
for (int i = 1; i < chars.length; i++) {
if (chars[i] == chars[i - 1]) {
count ++;
} else {
builder.append(count);
count = 1;
builder.append(chars[i]);
}
}
builder.append(count);
this.featureStr = builder.toString();
}
boolean match(SuperString string) {
if (this.featureStr.equals(string.featureStr) && ! this.raw.equals(string.raw)) {
return true;
}
return false;
}
}
}

