题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
思路:用三个List排序完成。 首先定义一个判断两个String是兄弟单词的方法,string1,string2转成char数组,再转list1,list2,排序后挨个比较,如果都一样,则为兄弟单词。 经过过滤的单词放入matchList<String>再按照字典排序,按照题目要求输出。
import java.util.*; public class BrotherWords { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { List<String> matchList = new ArrayList<>(); Set<String> strSet = new HashSet<>(); int num = in.nextInt(); String[] strs = new String[num]; for (int i = 0; i < num; i++) { strs[i] = in.next(); } String key = in.next(); int index = in.nextInt(); for (int i = 0; i < num; i++) {//去重 if (isBrother(key, strs[i])) { matchList.add(strs[i]); } } // List<String> matchList = new ArrayList<>(strSet); matchList.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); if (matchList.contains(key)) {//移除掉自己 matchList.remove(key); } int size = matchList.size(); System.out.println(size); if (index > size) { continue; } else { System.out.println(matchList.get(index - 1)); } } } private static boolean isBrother(String key, String str) { boolean flag = true; if (key.length() != str.length() || key.equals(str)) { flag = false; } else { int len = key.length(); char[] chars = key.toCharArray(); char[] chars1 = str.toCharArray(); List<Character> keyList = new ArrayList<>(); List<Character> charList = new ArrayList<>(); for (int i = 0; i < len; i++) { keyList.add(chars[i]); charList.add(chars1[i]); } keyList.sort(new Comparator<Character>() { @Override public int compare(Character o1, Character o2) { return o1.compareTo(o2); } }); charList.sort(new Comparator<Character>() { @Override public int compare(Character o1, Character o2) { return o1.compareTo(o2); } }); for (int i = 0; i < len; i++) {//排序后挨个比较 if (keyList.get(i) != charList.get(i)) { flag = false; } } } return flag; } }