public static int wordCount(String[] startWords, String[] targetWords) {
// 将每个startWord排序,存储所有startWord
Set<String> set = new HashSet<>();
for (String startWord : startWords) {
char[] chars = startWord.toCharArray();
Arrays.sort(chars);
set.add(new String(chars));
}
//将每个targetWord排序,再从中按顺序去除一个字符,看结果是否在set集合出现过
int count = 0;
for (String targetWord : targetWords) {
char[] chars = targetWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);
for (int i = 0; i < newWord.length(); i++) {
String subWord = newWord.substring(0, i) + newWord.substring(i + 1, newWord.length());//去除第i个字符
if (set.contains(subWord)) {
count++;
break;
}
}
}
return count;
}