LeetCode 299. 猜数字游戏
题目描述
思路分析
解法一:计数比较(推荐)
核心思路:
- 逐位比较统计公牛数(位置与数字都相同)。
- 其余数字分别计数,奶牛数为对应数字计数的最小值之和。
复杂度分析:
- 时间复杂度:O(n),其中 n 表示字符串长度。
- 空间复杂度:O(1),数字固定为 10 种。
class Solution {
public String getHint(String secret, String guess) {
int bulls = 0;
int[] cntS = new int[10];
int[] cntG = new int[10];
for (int i = 0; i < secret.length(); i++) {
char s = secret.charAt(i);
char g = guess.charAt(i);
if (s == g) {
bulls++;
} else {
cntS[s - '0']++;
cntG[g - '0']++;
}
}
int cows = 0;
for (int i = 0; i < 10; i++) {
cows += Math.min(cntS[i], cntG[i]);
}
return bulls + "A" + cows + "B";
}
}
func getHint(secret string, guess string) string {
bulls := 0
cntS := make([]int, 10)
cntG := make([]int, 10)
for i := 0; i < len(secret); i++ {
s := secret[i]
g := guess[i]
if s == g {
bulls++
} else {
cntS[s-'0']++
cntG[g-'0']++
}
}
cows := 0
for i := 0; i < 10; i++ {
if cntS[i] < cntG[i] {
cows += cntS[i]
} else {
cows += cntG[i]
}
}
return fmt.Sprintf("%dA%dB", bulls, cows)
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 299. 猜数字游戏 | 中等 | 计数 |
| 383. 赎金信 | 简单 | 计数 |
| 242. 有效的字母异位词 | 简单 | 计数 |
| 567. 字符串的排列 | 中等 | 计数 |
| 387. 字符串中的第一个唯一字符 | 简单 | 计数 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!