leetcode 299. 猜数字游戏

leetcode 299. 猜数字游戏

 

1.hash

leetcode 299. 猜数字游戏_第1张图片

class Solution {
    public String getHint(String secret, String guess) {
        char[] s1=new char[secret.length()];
        char[] g1=new char[guess.length()];
        int a=0;
        int b=0;

        s1=secret.toCharArray();
        g1=guess.toCharArray();

        for(int i=0 ; i<guess.length() ; i++){
            if(g1[i]==s1[i]){
                a++;
                //除去公牛
                g1[i]='#'; 
                s1[i]='&';
            }
        }

        for(int i=0 ; i<guess.length() ; i++){
            for(int j=0 ; j<secret.length() ; j++){
                if(s1[j]==g1[i]){
                    b++;
                    //除去奶牛
                    s1[j]='&';
                    break;
                }
            }
        }

        return a+"A"+b+"B";
    }
}

 


 

2.match

leetcode 299. 猜数字游戏_第2张图片

class Solution {
    public String getHint(String secret, String guess) {
        char[] s1=new char[secret.length()];
        char[] g1=new char[guess.length()];
        int[] num_s=new int[10];
        int[] num_g=new int[10];
        int a=0;
        int b=0;

        s1=secret.toCharArray();
        g1=guess.toCharArray();

        for(int i=0 ; i<guess.length() ; i++){
            if(g1[i]==s1[i]){
                a++;
                g1[i]='#';
                s1[i]='&';
            }
        }

        for(int i=0 ; i<secret.length() ; i++){
            if(s1[i]!='&'){
                num_s[s1[i]-48]++;
            }        
        }

        for(int i=0 ; i<guess.length() ; i++){
            if(g1[i]!='#'){
                num_g[g1[i]-48]++;
            }        
        }

        for(int i=0 ; i<10 ; i++){
            b=b+(num_s[i]>num_g[i]?num_g[i]:num_s[i]);
        }

        return a+"A"+b+"B";
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)