[Swift]LeetCode299. 猜数字游戏 | Bulls and Cows
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10241354.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.
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.
Please note that both secret number and friend's guess may contain duplicate digits.
Example 1:
1
3
8
0
1
7.
Example 2:
1
1
Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。
请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A
表示公牛,用 B
表示奶牛。
请注意秘密数字和朋友的猜测数都可能含有重复数字。
示例 1:
1
3
8
0
1
7
示例 2:
1
1
说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等。
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了