★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mxgiobmh-ku.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.git
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. github
Please note that both secret number and friend's guess may contain duplicate digits.微信
Example 1:ide
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: bull and cows. The bull is , the cows are , and 138017.
Example 2:函數
Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: The 1st in friend's guess is a bull, the 2nd or 3rd is a cow.11
Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.spa
你正在和你的朋友玩 猜數字(Bulls and Cows)遊戲:你寫下一個數字讓你的朋友猜。每次他猜想後,你給他一個提示,告訴他有多少位數字和確切位置都猜對了(稱爲「Bulls」, 公牛),有多少位數字猜對了可是位置不對(稱爲「Cows」, 奶牛)。你的朋友將會根據提示繼續猜,直到猜出祕密數字。code
請寫出一個根據祕密數字和朋友的猜想數返回提示的函數,用 A
表示公牛,用 B
表示奶牛。htm
請注意祕密數字和朋友的猜想數均可能含有重複數字。blog
示例 1:
輸入: secret = "1807", guess = "7810" 輸出: "1A3B" 解釋: 公牛和 奶牛。公牛是 ,奶牛是 , 和 。138017
示例 2:
輸入: secret = "1123", guess = "0111" 輸出: "1A1B" 解釋: 朋友猜想數中的第一個 是公牛,第二個或第三個 可被視爲奶牛。11
說明: 你能夠假設祕密數字和朋友的猜想數都只包含數字,而且它們的長度永遠相等。
40ms
1 class Solution { 2 func getHint(_ secret: String, _ guess: String) -> String { 3 4 var acount = 0 5 var bcount = 0 6 7 var secArr = Array(secret) 8 var gueArr = Array(guess) 9 10 for i in 0..<secArr.count where secArr[i] == gueArr[i] { 11 acount += 1 12 secArr[i] = "a" 13 gueArr[i] = "b" 14 } 15 16 secArr = secArr.filter{return $0 != "a"} 17 gueArr = gueArr.filter{return $0 != "b"} 18 19 for i in 0..<gueArr.count { 20 let gue = gueArr[i] 21 22 for j in 0..<secArr.count where secArr[j] == gue { 23 bcount += 1 24 secArr.remove(at: j) 25 break 26 } 27 28 } 29 30 return "\(acount)A\(bcount)B" 31 } 32 }