Wednesday, November 7, 2018
299. Bulls and Cows
看上去比较简单但是其实很厉害的题,而且第一遍也没做对
感觉是一个变相的Two Pointers的题
重点是什么时候countB 满足条件
1.当secret扫过去的时候,如果map里面char是负的count,证明有多余的guess里面的char等待被match
2.当guess扫过去的时候,如果map里面char是正count,证明secret里已经有一些这个char了,可以直接match
所以i每扫一次有两次增加的机会
18.73 %
class Solution {
public String getHint(String secret, String guess) {
if (secret == null || guess == null || secret.length() != guess.length()) {
return null;
}
int countA = 0; // both same
int countB = 0;
// key->num, value->count
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < secret.length(); i++) {
char s = secret.charAt(i);
char g = guess.charAt(i);
if (s == g) {
countA++;
} else {
if (map.getOrDefault(s, 0) < 0) {
countB++;
}
map.put(s, 1 + map.getOrDefault(s, 0));
if (map.getOrDefault(g, 0) > 0) {
countB++;
}
map.put(g, map.getOrDefault(g, 0) - 1);
}
}
return countA + "A" + countB + "B";
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment