题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int wordCount = in.nextInt(); String[] words = new String[wordCount]; for (int i = 0; i < wordCount; i++) { words[i] = in.next(); } String x = in.next(); int k = in.nextInt(); int brotherWordCount = 0; List<String> wordList = new ArrayList<>(); for (int i = 0; i < wordCount; i++) { // 通过短路来快速排除不可能是兄弟单词的单词 if (maybeBrother(x, words[i]) && !words[i].equals(x) && sort(words[i]).equals(sort(x))) { brotherWordCount++; wordList.add(words[i]); } } // JDK1.8的stream不支持下面这种写法 JDK16开始支持 // List<String> dict = wordList.stream().sorted().toList(); List<String> dict = wordList.stream().sorted().collect(Collectors.toList()); // 如果给定的单词里不存在兄弟单词 则不输出 System.out.println(brotherWordCount + "\n" + (k - 1 < dict.size() ? dict.get(k - 1) : "")); } // 如果两个单词长度不等 一定不是兄弟单词 static boolean maybeBrother(String s1, String s2) { return s1.length() == s2.length(); } // 对单词按每个字排序 static String sort(String word) { return Stream.of(word.split("")).sorted().reduce((x, y) -> x + y).orElse(null); } }
#华为笔试#