Clean and clear Java O(n) Solution


  • 4
    X
    public class Solution {
        public String getHint(String secret, String guess) {
            int A = 0, B = 0;
            int[] cnt = new int[10];
            for(int i=0; i<secret.length(); ++i){
                if(secret.charAt(i) == guess.charAt(i)) ++A;
                else{
                    if(++cnt[secret.charAt(i)-'0'] <= 0)    ++B;
                    if(--cnt[guess.charAt(i)-'0']>=0)   ++B;
                }
            }
            return A + "A" + B + "B";
        }
    }

Log in to reply
 

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