Easy and efficient Java solution


  • 1
    K

    The idea is simple. Go through the strings and compare characters at similar indices. If they are the same, increment countA. If they are different, we are going to use an array, counts, to remember what we have seen. If we have seen it in the secret, we will record that as a positive number. A guess will be remembered as a negative number.

    Each time we encounter a secret, if the count of that number is negative, increment countB, then increment the count of that secret number.
    Each time we encounter a guess, if the count of that guess is positive, increment countB, then decrement the count of that guess number.

    public class Solution {
    public String getHint(String secret, String guess) {
        int countA = 0;
        int countB = 0;
        int[] counts = new int[10];
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) {
                countA++;
            } else {
                int secretNum = secret.charAt(i) - '0';
                int guessNum = guess.charAt(i) - '0';
                if (counts[secretNum] < 0) { // if the guess contained this number so far
                    countB++;
                }
                counts[secretNum]++; // secret counts are positive
                if (counts[guessNum] > 0) { // if the secret contained this number so far
                    countB++;
                }
                counts[guessNum]--; // guess counts are negative
            }
            
        }
        return countA + "A" + countB + "B";
    }
    

    }


Log in to reply
 

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