题解 | 查找兄弟单词

查找兄弟单词

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str=in.nextLine();
        String[] strs=str.split(" ");
        int n=Integer.parseInt(strs[0]);
        int k=Integer.parseInt(strs[strs.length-1]);
        String x=strs[strs.length-2];
        char[] xChar=x.toCharArray();
        Arrays.sort(xChar);

        List<String> xd_list=new ArrayList<>();
        List<char[]> list=new ArrayList<>(); 
        for(int i=1;i<n+1;i++){
            if(!strs[i].equals(x)){
                char[] chars=strs[i].toCharArray();
                Arrays.sort(chars);
                if(Arrays.equals(chars,xChar)){
                    xd_list.add(strs[i]);
                    list.add(chars);
                }
            }
        }

        
        
        int res=xd_list.size();
        String[] xd_str=xd_list.toArray(new String[0]);
        Arrays.sort(xd_str);
        System.out.println(res);
        if(res!=0&&k<=res){
            System.out.println(xd_str[k-1]);
        }
    }
}

这要注意比较两个字符串是否相等不能用!=,要用equals(),比较两个数组是否相等要用Arrays.equals()

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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