查找兄弟单词_乒乓球筐

查找兄弟单词

查找兄弟单词

image-20220524155844667

import java.util.*;
public class  Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //一行以空格分割!!!
        String[] strs = sc.nextLine().split(" ");
        int len = strs.length;
        int n = Integer.parseInt(strs[0]);//获取到 n
        int k = Integer.parseInt(strs[len-1]);//获取到 k !
        String target = strs[len-2];//目标单词!
        char[] arr = target.toCharArray();
        Arrays.sort(arr);
        String target1 = new String(arr);//排成了字典序用于比较!这里不能用toString!!!因为toString有[ ]
        ArrayList<String> table = new ArrayList<>();//将兄弟单词保存!
        for(int i = 1;i< n ;i++){
            //遍历查找兄弟单词!!!
            String tmp = strs[i];
            if(target.length()!=tmp.length()){
                //长度不相等 不是兄弟!
                continue;
            }else if(strs[i].equals(target)){
                //相等不是兄弟!
                continue;
            }else{
                //两个字符串排序后相等就是好兄弟!
                char[] tmp1 = tmp.toCharArray();
                Arrays.sort(tmp1);

                if((new String(tmp1)).equals(target1)){
                    table.add(tmp);
                }
            }
        }
        //排序
        Collections.sort(table);
        if(table.size()!=0){
             System.out.println(table.size());
            if(k<=table.size())
            System.out.println(table.get(k-1));
        }else {
            System.out.println(0);
        }
    }
}
  • 注意细节 这里的targettmp字符串可能单词有重复,例如abbcaccb如果通过contains`会出错!
  • 这里用判断相等不能用toString,要通过new String()
  • 注意输出!!! 不要越界!

乒乓球筐

乒乓球筐

image-20220524163022655

// write your code here
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        // int[] table = new int[26]; error 应该放在循环里!!!
        while(sc.hasNext()){
            int[] table = new int[26];
            String[] str = sc.nextLine().split(" ");
            String strA = str[0];
            String strB = str[1];
            for(int i = 0;i< strA.length();i++){
                //统计每个字母个数
                table[strA.charAt(i)-'A']++;
            }
            boolean flg = false;
            for(int i = 0;i< strB.length();i++){
                //判断!打擂台!!!
                if((--table[strB.charAt(i)-'A'])==-1){
                    //说明不符合!
                    flg=true;
                    System.out.println("No");
                    break;
                }
            }
            if(!flg){
                System.out.println("Yes");
            }
        }
    }
}
#笔试#
全部评论
细节很重要细节决定成败
点赞 回复 分享
发布于 2022-08-27 13:08 河南

相关推荐

评论
点赞
收藏
分享

创作者周榜

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