题解 | #查找兄弟单词#

查找兄弟单词

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;
    }
}

全部评论

相关推荐

迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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