My code:
public class Solution {
public String getHint(String secret, String guess) {
if (secret == null || guess == null) {
return null;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int bull = 0;
for (int i = 0; i < secret.length(); i++) {
if (secret.charAt(i) == guess.charAt(i)) {
bull++;
}
else {
if (!map.containsKey(secret.charAt(i))) {
map.put(secret.charAt(i), 1);
}
else {
map.put(secret.charAt(i), map.get(secret.charAt(i)) + 1);
}
}
}
int cow = 0;
for (int i = 0; i < secret.length(); i++) {
if (secret.charAt(i) != guess.charAt(i) && map.containsKey(guess.charAt(i))) {
if (map.get(guess.charAt(i)) > 0) {
cow++;
map.put(guess.charAt(i), map.get(guess.charAt(i)) - 1);
}
}
}
return bull + "A" + cow + "B";
}
}
reference:
https://discuss.leetcode.com/topic/28445/c-4ms-straight-forward-solution-two-pass-o-n-time/9
没做出来。。。
其实应该是扫两遍。第一次把match的找出来计数。同时把不 match 的记录在hashmap 中。
第二遍,把不匹配的都统计出来。
并不难,只是要分两步走。
Java HashMap get 操作,如果key不存在于 map中,就返回 null
Anyway, Good luck, Richardo! — 09/22/2016