题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); ArrayList<String> inputList = new ArrayList<>(); for (int i = 0; i < size; i++) { String next = scanner.next(); inputList.add(next); } String oldStr = scanner.next(); int index = scanner.nextInt(); ArrayList<String> brotherList = new ArrayList<>(); for (String s : inputList) { if (isBrother(oldStr, s)) { brotherList.add(s); } } Collections.sort(brotherList); System.out.println(brotherList.size()); if (index <= brotherList.size()) { System.out.println(brotherList.get(index - 1)); } } public static boolean isBrother(String oldStr, String newStr) { if (oldStr.length() != newStr.length() || oldStr.equals(newStr)) { return false; } char[] charArray = oldStr.toCharArray(); char[] toCharArray = newStr.toCharArray(); Arrays.sort(charArray); Arrays.sort(toCharArray); for (int i = 0; i < charArray.length; i++) { if (charArray[i] != toCharArray[i]) { return false; } } return true; } }