题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.Scanner; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<String> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.next()); } String word = scanner.next(); int k = scanner.nextInt(); // TreeSet会自动排序,也就是按字典序排序,但不能直接输出,需要转换为list // TreeSet<String> broList=new TreeSet<>(); List<String> broList = new ArrayList<>(); char[] charArray = word.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (char c : charArray) map.put(c, map.getOrDefault(c, 0) + 1); int num = 0; for (String s : list) { if (s.equals(word) || s.length() != word.length()) continue; char[] cur = s.toCharArray(); Map<Character, Integer> checkMap = new HashMap<>(); for (char c : cur) { if (map.containsKey(c)) checkMap.put(c, checkMap.getOrDefault(c, 0) + 1); } AtomicInteger j = new AtomicInteger(); map.keySet().forEach(key -> { if (!Objects.equals(map.get(key), checkMap.get(key))) j.set(1); }); if (j.get() == 0) { num++; broList.add(s); } } System.out.println(num); Collections.sort(broList); if (k <= broList.size()) // System.out.println(new ArrayList<>(broList).get(k-1)); System.out.println(broList.get(k - 1)); } } 本来以为用treemap存找到的兄弟单词就好了,省去排序了,结果只通过了八个,结果还是需要用list再排序,因为兄弟单词可以重复