299. Bulls and Cows [Medium]
作者:互联网
/**
* Runtime: 18 ms, faster than 11.23%
* Memory Usage: 39 MB, less than 67.38%
*/
class Solution {
public String getHint(String secret, String guess) {
int a = 0, b = 0;
char[] sec = secret.toCharArray();
char[] gue = guess.toCharArray();
// find all a
for (int i = 0; i < sec.length; i++) {
if (sec[i] == gue[i]) {
a++;
sec[i] = 'n';
gue[i] = 'n';
}
}
// find all b
for (int i = 0; i < sec.length; i++) {
if (sec[i] != 'n') {
int idx = guess.indexOf(sec[i]);
while (idx != -1 && gue[idx] == 'n') {
idx = guess.indexOf(sec[i], idx + 1);
}
if (idx != -1) {
b++;
gue[idx] = 'n';
}
}
}
// form the result string
StringBuilder sb = new StringBuilder();
sb.append(a).append("A").append(b).append("B");
return sb.toString();
}
}
标签:guess,Medium,idx,gue,int,Bulls,sec,Cows,append 来源: https://blog.csdn.net/Squirrelmi/article/details/120453219