题解 | #查找兄弟单词#

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String s = null;
        s = bf.readLine();
        //准备一个list接收字典中满足要求的兄弟单词
        ArrayList list = new ArrayList();
        String[] split = s.split(" ");
        //获取字典中单词的数量
        int n = Integer.parseInt(split[0]);
        //指定查找的单词
        String findContent = split[split.length - 2];
        //指定输出排序后的第几个单词
        int index = Integer.parseInt(split[split.length - 1]);
        for (int i = 1; i <= n; i++) {
            char[] chars = findContent.toCharArray();
            String brotherWord = split[i].toString();
            char[] brotherArray = brotherWord.toCharArray();
            //兄弟单词要求和原来的单词不同。例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。
            if (brotherWord.equals(findContent)) {
                continue;
            }
            //交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。
            Arrays.sort(chars);
            Arrays.sort(brotherArray);
            //判断排序后的数组是否属于兄弟单词
            if (Arrays.toString(brotherArray).equals(Arrays.toString(chars))) {
                list.add(split[i]);
            }
        }
        //输出兄弟单词的个数
        System.out.println(list.size());
        //对兄弟单词列表进行排序
        Collections.sort(list);
        if (index <= list.size()) {
            System.out.println(list.get(index - 1));
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务