题解 | #查找兄弟单词#

查找兄弟单词

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

非常麻烦的一题,要考虑的东西有点多。。。

我采用的方法是先去重(重复的不算兄弟单词),然后给目标字符串排序,剩下的字符串再依次排完序再与目标字符串比较,相同就说明是兄弟单词,然后添加到resList里面,再给resList排序即可得到想要的第n个兄弟单词

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String s = sc.next();
            list.add(s);
        }
        String target = sc.next();
        int index = sc.nextInt();

        int resCount = 0;
        for (int i = 0; i < list.size(); i++) {     // 去重
            String s = list.get(i);
            if (s.equals(target)) {
                list.remove(i);
                i--;
            }
        }

        List<Character> tempTarget = new ArrayList<>();
        for (int i = 0; i < target.length(); i++) {     //给目标字符串排序
            tempTarget.add(target.charAt(i));
        }
        Collections.sort(tempTarget);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tempTarget.size(); i++) {
            sb.append(tempTarget.get(i));
        }
        target = sb.toString();

        List<String> resList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {     // 获取兄弟字符集合
            String s = list.get(i);
            //System.out.println("当前字符串是:" + s);
            List<Character> tempList = new ArrayList<>();
            for (int j = 0; j < s.length(); j++) {
                tempList.add(s.charAt(j));
            }
            Collections.sort(tempList);
            StringBuilder tempSB = new StringBuilder();
            for (int j = 0; j < tempList.size(); j++) {
                tempSB.append(tempList.get(j));
            }
            //System.out.println("当前sb是:" + tempSB);
            if (tempSB.toString().equals(target)) {
                resCount++;
                resList.add(s);
            }
        }

        Collections.sort(resList);
        System.out.println(resCount);
        if (resList.size() >= index) {
            System.out.println(resList.get(index - 1));
        }
    }
}

全部评论

相关推荐

面了100年面试不知...:头像换成柯南再试试
点赞 评论 收藏
分享
09-13 17:25
亲切的00后在笔试:我也遇到了,所以我早他一步查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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