您现在的位置是:亿华云 > 系统运维

LeetCode之电话号码的字母组合

亿华云2025-10-04 01:04:22【系统运维】3人已围观

简介前言我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。微博:@故胤道长[1])的 Swift 算法题题解整理为文字版以方便大家学习与阅读。LeetCode

前言

我们社区陆续会将顾毅(Netflix 增长黑客,电字母组合《iOS 面试之道》作者,话号ACE 职业健身教练。电字母组合微博:@故胤道长[1])的话号 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新了 16 期,电字母组合我们会保持更新时间和进度(周一、话号周三、电字母组合周五早上 9:00 发布),话号每期的电字母组合内容不多,我们希望大家可以在上班路上阅读,话号长久积累会有很大提升。香港云服务器电字母组合

不积跬步,话号无以至千里;不积小流,电字母组合无以成江海,话号Swift社区 伴你前行。电字母组合如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:中等

1. 描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。源码下载

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

2. 示例

示例 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] 的一个数字

3. 答案

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]     } }  主要思想:经典的深度优先搜索,首先创建电话板 时间复杂度:O(4^n), n 表示数字长度 空间复杂度:O(n), n 表示数字长度

该算法题解的仓库:LeetCode-Swift[2]

点击前往 LeetCode[3] 练习

参考资料

[1]@故胤道长:

https://m.weibo.cn/u/1827884772

[2]LeetCode-Swift:

https://github.com/soapyigu/LeetCode-Swift[3]LeetCode: https://leetcode.com/problems/letter-combinations-of-a-phone-number

很赞哦!(632)