java解决方法

查找兄弟单词

http://www.nowcoder.com/questionTerminal/03ba8aeeef73400ca7a37a5f3370fe68

import java.util.*;

public class Main{
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    while (scan.hasNext()) {
      int size = scan.nextInt();
      ArrayList<String> words = new ArrayList<>();
      for (int i = 0; i < size; i++) {
        words.add(scan.next());
      }
      String target = scan.next();
      String sortedTarget = getSortedWord(target);
      int k = scan.nextInt();
      ArrayList<String> brothers = new ArrayList<>();
      for (String s : words) {
        if (!s.equals(target) && getSortedWord(s).equals(sortedTarget)) {
          brothers.add(s);
        }
      }
      System.out.println(brothers.size());
      if (brothers.size() >= k) {
        Collections.sort(brothers);
        System.out.println(brothers.get(k - 1));
      }
    }
  }

  private static String getSortedWord(String s) {
    char[] arr = s.toCharArray();
    Arrays.sort(arr);
    return new String(arr);
  }
}
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务