天天看點

[LeetCode] 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: “7810”

hint: 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 <code>"1a3b"</code>.

please note that both secret number and friend’s guess may contain duplicate digits, for example:

secret number: “1123” friend’s guess: “0111”

in this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return <code>"1a1b"</code>.

you may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

掃描secret字元串,記錄各個字元的個數。

掃描兩遍guess字元串:

①第一遍記錄字元正确且位置也正确的字元。

②第二遍記錄字元正确但位置不正确的字元。

c++:

java: