Java HashMap solution


  • 2
    Q
    public class Solution {
        public String getHint(String secret, String guess) {
    		int a=0;
    		int b=0;
    		Map<Character, Integer> secretChars = new HashMap<Character, Integer>();
    		for (char c:secret.toCharArray())
    			if (secretChars.containsKey(c))
    				secretChars.put(c, secretChars.get(c)+1);
    			else
    				secretChars.put(c, 1);
    				
    		for (int i=0;i<guess.length();i++){
    			char c = guess.charAt(i);
    			if (c == secret.charAt(i)){
    				a++;
    				Integer newVal = secretChars.get(c)-1;
    				if (newVal == 0)
    					secretChars.remove(c);
    				else
    					secretChars.put(c, newVal);
    			}
    		}
    		for (int i=0;i<guess.length();i++){
    			char c = guess.charAt(i);
    			if (c != secret.charAt(i)){
    				Integer val = secretChars.get(c);
    				if (val!=null){
    					b++;
    					Integer newVal = val-1;
    					if (newVal == 0)
    						secretChars.remove(c);
    					else
    						secretChars.put(c, newVal);
    				}
    			}
    		}
    		return a+"A"+b+"B";
        }
    }

  • 1
    Q

    Simplified to single pass.

    public class Solution {
        public String getHint(String secret, String guess) {
    		int a=0,b=0;
    		Map<Character, Integer> secretChars = new HashMap<Character, Integer>();
    		for (char c:secret.toCharArray())
    			secretChars.put(c, secretChars.get(c)==null?1:secretChars.get(c)+1);
    		for (int i=0;i<guess.length();i++){
    			char c = guess.charAt(i);
    			Integer val = secretChars.get(c)==null?0:secretChars.get(c);
    			if (c == secret.charAt(i)){
    			    a++;
    			    if (val<=0)
    				    b--;
    			}
    			else if (val>0)
    			    b++;
    			secretChars.put(c, val-1);
    		}
    		return a+"A"+b+"B";
        }
    }

  • 0
    Q

    Based on Stan's idea of b = all - a

    public class Solution {
        public String getHint(String secret, String guess) {
    		Map<Character, Integer> secretChars = new HashMap<Character, Integer>();
    		Map<Character, Integer> guessChars = new HashMap<Character, Integer>();
    		for (char c:secret.toCharArray())
    			secretChars.put(c, secretChars.get(c)==null?1:secretChars.get(c)+1);
    		for (char c:guess.toCharArray())
    			guessChars.put(c, guessChars.get(c)==null?1:guessChars.get(c)+1);
    		int a=0,all = 0;
    		for (int i=0;i<guess.length();i++){
    			if (guess.charAt(i) == secret.charAt(i))
    				a++;
    		}
    		Iterator<Character> secretIter = secretChars.keySet().iterator();
    		while (secretIter.hasNext()){
    			char c = secretIter.next();
    			all = all+Math.min(secretChars.get(c),
    					(guessChars.get(c)!=null?guessChars.get(c):0));
    		}
    		return a+"A"+(all-a)+"B";
        }
    }

Log in to reply
 

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