这道题感觉也真是给自己新知,自己一开始有点蒙,尤其是想就一次循环把两只牛都求出来。一次求其实可以,但确实一上来有难度,这个在平时也就罢了,但在面试时咋办啊。退而求其次,就一点,找到一个能work的方法也行。
下面的做法是参考了一种两次循环的比较好的。
第一次for,求出bull的数量,同时将secret的其它字符连带数量存入map,
第二次for,求出cow的数量,比对guess
这种妥协需要有。另外今后可参考点击打开链接
public class Solution {
public String getHint(String secret, String guess) {
String result = "";
if (secret == null || secret.length() == 0 || guess == null || guess.length() == 0) {
return result;
}
Map<Character/*secretChar*/, Integer/*quantity*/> map = new HashMap<>();
int bullCount = 0;
for (int i = 0; i < secret.length(); i++) {
if (secret.charAt(i) == guess.charAt(i)) {
bullCount++;
} else {
if (map.containsKey(secret.charAt(i))) {
map.put(secret.charAt(i), map.get(secret.charAt(i)) + 1);
} else {
map.put(secret.charAt(i), 1);
}
}
}
int cowCount = 0;
for (int i = 0; i < secret.length(); i++) {
if (secret.charAt(i) != guess.charAt(i)) {
if (map.containsKey(guess.charAt(i))) {
cowCount++;
if (map.get(guess.charAt(i)) == 1) {
map.remove(guess.charAt(i));
} else {
map.put(guess.charAt(i), map.get(guess.charAt(i)) - 1);
}
}
}
}
return bullCount + "A" + cowCount + "B";
}
}