题解 | #查找兄弟单词#

查找兄弟单词

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

全部评论

相关推荐

剑桥断刀:找啥工作,牛客找个比如大厂软开或者随便啥的高薪牛马,大把没碰过妹子的技术仔,狠狠拿捏爆金币
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务