题目:https://leetcode.com/problems/bulls-and-cows/
You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.
For example:
Secret number: 1807 Friend's guess: 7810Hint:
1
bull and
3
cows. (The bull is
8
, the cows are 0
, 1
and 7
.)
Write a function to return a hint according to the secret number and friend's guess, use A
to indicate the bulls and B
to indicate the cows, in the above example, your function should return 1A3B
.
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
/* 思路:统计两个字符串中位置相同且数字相同和位置不同而数字相同的数目。
* 两次遍历。1.统计位置相同且数字相同个数。且将位置不同的字母都保存。
* 2.统计含有相同数字的个数。
*/
public class Solution{
public String getHint(String secret, String guess) {
int countA = 0, countB = 0;
LinkedList<Character> cur = new LinkedList<Character>();
LinkedList<Integer> index = new LinkedList<Integer>();
for(int i = 0; i < secret.length(); i++) {
if(secret.charAt(i) == guess.charAt(i)) {
countA++;
} else {
index.offer(i);
cur.add(secret.charAt(i));
}
}
while(!index.isEmpty()) {
char ch = guess.charAt(index.poll());
if(cur.contains(ch)) {
countB++;
//ch需要转换为Character
cur.remove(Character.valueOf(ch));
}
}
return Integer.toString(countA) + "A" + Integer.toString(countB) + "B";
}
}