思路:
关键是理解题意:
A的意思是位置正确且数字正确的个数;
B的意思是位置不正确但数字正确的个数。
public class Solution {
public String getHint(String secret, String guess) {
char[] sc = secret.toCharArray();
char[] gc = guess.toCharArray();
int[] secret_digits = new int[10];
int[] guees_digits = new int[10];
int A = 0, total = 0;
for(int i = 0; i < secret.length(); ++i) {
secret_digits[sc[i] - '0']++;
guees_digits[gc[i] - '0']++;
if(sc[i] == gc[i]) A++;
}
for(int i = 0; i < 10; ++i) {
total += Integer.min(secret_digits[i], guees_digits[i]);
}
String ans = A + "A" + (total - A) + "B";
return ans;
}
}
本文介绍了一种猜数字游戏的算法实现,通过计算位置正确(A)及位置错误但数字正确(B)的数量来给出提示。文章详细解释了如何利用字符数组和整型数组统计秘密数字与猜测数字之间的匹配情况。
744

被折叠的 条评论
为什么被折叠?



