Easy Java Solution. Using hash map.


  • 3
    O
    public class Solution {
        public String getHint(String secret, String guess) {
            int i, bulls = 0, cows = 0, size = secret.length();
            char s, g;
            int[] hMap = new int[256];
            for(i = 0; i < size; i++) {
                s = secret.charAt(i);
                g = guess.charAt(i);
                if (s == g) {
                    bulls++;
                } else {
                    hMap[s-'\0']++;
                }
            }
            for(i = 0; i < size; i++) {
                g = guess.charAt(i);
                s = secret.charAt(i);
                if(hMap[g-'\0'] > 0 && g != s) {
                    cows++;
                    hMap[g-'\0']--;
                }
            }
            
            return bulls+"A"+cows+"B";
        }
    }
    

  • 1
    J

    @aleksey.danilevsky.5

    a suggestion: you only need to create size=10 hMap
    because the test case only contain digits hMap[s-'0'] needs only 10 space.


  • 0
    O

    @Jonathan001 Yes it is true. Thanks. But it is still O(1) space complexity.


Log in to reply
 

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