Wednesday, December 2, 2015

[leetcode]Bull and Cows

有时候要再三审视思路...因为未必是对的.. 最好先弄个小test case 想好思路想一想. 思路分两步走 先找matched 顺便把不match的入hash, 然后再找不match 还有一个更高效的方法是用counter...下次记得用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution {
    public String getHint(String secret, String guess) {
        HashMap<Character, Integer> lookup = new HashMap<Character, Integer>();
        int matched = 0;
        int hasNum = 0;
        for (int i = 0; i < secret.length(); i++){
            char sechar = secret.charAt(i);
            char guchar = guess.charAt(i);
            if (sechar == guchar) matched++;
            else{
                int count = 1;
                if (lookup.containsKey(sechar)){
                    count += lookup.get(sechar);
                }
                lookup.put(sechar, count);
            }
        }
        for (int i = 0; i < guess.length(); i++){
            char guchar = guess.charAt(i);
            char sechar = secret.charAt(i);
            if (guchar != sechar && lookup.containsKey(guchar)){
                int count = lookup.get(guchar)-1;
                if (count == 0) lookup.remove(guchar);
                else lookup.put(guchar, count);
                if (guchar == sechar) matched++;
                else hasNum++;
            }    
        }
        
        return matched+"A"+hasNum+"B";
    }
}

No comments:

Post a Comment