Using Arrays to Enhance The Performance


  • 0
    S
    public class Solution {
        public String getHint(String secret, String guess) {
            StringBuilder sb = new StringBuilder();
            int[] setS = new int[10];
            int[] setG = new int[10];
            int bull = 0, cow = 0;
            if(secret==null||secret.length()==0) return sb.toString();
            for(int i=0; i<guess.length(); i++){
                if(secret.charAt(i)==guess.charAt(i)) bull++;
                else{
                    int sVal = Character.getNumericValue(secret.charAt(i));
                    int gVal = Character.getNumericValue(guess.charAt(i));
                    if(setG[sVal]>0){
                        setG[sVal]--;
                        cow++;
                    }else{
                        setS[sVal]++;
                    }
                    if(setS[gVal]>0){
                        setS[gVal]--;
                        cow++;
                    }else{
                        setG[gVal]++;
                    }
                }
            }
            return sb.append(bull).append('A').append(cow).append('B').toString();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.