Question
Solution
题目大意:有一串隐藏的号码,另一个人会猜一串号码(数目相同),如果号码数字与位置都对了,给一个bull,数字对但位置不对给一个cow,注:数字对与位置对优先,一个号码不能重复判断.
思路:构造map结构,遍历实现
Java实现:实现的不漂亮,好歹能通过
public String getHint(String secret, String guess) {
Map<Character, Index> map = new HashMap<>();
for (int i=0; i<secret.length(); i++) {
Index idx = map.get(secret.charAt(i));
if (idx == null) {
idx = new Index();
map.put(secret.charAt(i), idx);
}
idx.add(i);
}
int bulls = 0;
int cows = 0;
List<Character> cowsList = new ArrayList<>(); // for count cows
// count bulls
for (int i=0; i<guess.length(); i++) {
Index idx = map.get(guess.charAt(i));
if (idx != null) { // check digits
if (idx.isBull(i)) {
bulls++;
} else {
cowsList.add(guess.charAt(i));
}
}
}
// count cows
for (char c : cowsList) {
Index idx = map.get(c);
if (idx.isCow()) {
cows++;
}
}
return bulls + "A" + cows + "B";
}
class Index {
List<Integer> idxList;
int count;
// constructor
public Index() {
idxList = new ArrayList<>();
count = 0;
}
void add(int x) {
idxList.add(x);
count++;
}
boolean isCow() {
return count-- > 0;
}
boolean isBull(int x) {
for (int tmp : idxList) {
if (x == tmp) {
count--;
return true;
}
}
return false;
}
}
Ref
https://leetcode.com/problems/bulls-and-cows/discuss/74621/One-pass-Java-solution
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] numbers = new int[10];
for (int i = 0; i<secret.length(); i++) {
int s = Character.getNumericValue(secret.charAt(i));
int g = Character.getNumericValue(guess.charAt(i));
if (s == g) bulls++;
else {
if (numbers[s] < 0) cows++;
if (numbers[g] > 0) cows++;
numbers[s] ++;
numbers[g] --;
}
}
return bulls + "A" + cows + "B";
}
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] numbers = new int[10];
for (int i = 0; i<secret.length(); i++) {
if (secret.charAt(i) == guess.charAt(i)) bulls++;
else {
if (numbers[secret.charAt(i)-'0']++ < 0) cows++;
if (numbers[guess.charAt(i)-'0']-- > 0) cows++;
}
}
return bulls + "A" + cows + "B";
}