我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。
LeetCode 算法到目前我们已经更新了 16 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
难度水平:中等
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2
输入:digits = "" 输出:[]
示例 3
输入:digits = "2" 输出:["a","b","c"]
约束条件:
0 <= digits.length <= 4
digits[i]
是范围 ['2', '9']
的一个数字class LetterCombinationsPhoneNumber { func letterCombinations(_ digits: String) -> [String] { guard digits.count > 0 else { return [String]()}var combinations = [String](), combination = ""let numberToStr = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]dfs(&combinations, &combination, numberToStr, digits, 0)return combinations}private func dfs(_ combinations: inout [String], _ combination: inout String, _ numberToStr: [String], _ digits: String, _ index: Int) { if combination.count == digits.count { combinations.append(combination)return}let currentStr = fetchCurrentStr(from: digits, at: index, numberToStr)for char in currentStr { combination.append(char)dfs(&combinations, &combination, numberToStr, digits, index + 1)combination.removeLast()}}private func fetchCurrentStr(from digits: String, at index: Int, _ numberToStr: [String]) -> String { guard index >= 0 && index < digits.count else { fatalError("Invalid index")}let currentDigitChar = digits[digits.index(digits.startIndex, offsetBy: index)]guard let currentDigit = Int(String(currentDigitChar)), currentDigit >= 0, currentDigit < numberToStr.count else { fatalError("Invalid digits")}return numberToStr[currentDigit]}}
该算法题解的仓库:LeetCode-Swift
点击前往 LeetCode 练习
我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者