为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode17. 电话号码的字母组合 | Letter Combinations of a Phone Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9888168.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.


 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。


 8ms

 1 class Solution {
 2     let strings:[String] = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
 3     func letterCombinations(_ digits: String) -> [String] {
 4         var res:[String] = [String]()
 5         if digits.isEmpty {return res}
 6          //回溯法
 7         backtracking("",digits,0, &res)
 8         return res
 9     }
10     func backtracking(_ s:String ,_ digits:String,_ flag:Int,_ res:inout[String])
11     {
12       
13         //如果已经遍历完所有输入的数字,说明已经到达底部,需要向上溯源。
14         if flag >= digits.count
15         {
16             //到达底部说明已经是完整的一个结果,则将此次结果添加到结果集中
17             res.append(s);
18             //返回,向上回溯
19             return;
20         }
21         //0的ASCII:48
22         var chars:String = strings[digits.toInt(flag) - 48]
23         for char in chars.characters
24         {
25             var str:String = s + String(char)
26             backtracking(str,digits,flag+1,&res)
27         }
28     }
29 }
30 
31 extension String {
32     //获取指定索引位置的字符,返回为字符串形式
33     func charAt(_ num:Int) -> String
34     {
35         guard num < self.count else {
36             assertionFailure("index out of range!")
37             return String()
38         }
39         let index = self.index(self.startIndex,offsetBy: num)
40         return String(self[index])
41     }
42     
43     //获取指定索引位置字符的ASCII整数值
44     func toInt(_ num:Int) -> Int
45     {
46         guard num < self.count else {
47             assertionFailure("index out of range!")
48             return 0
49         }
50         var number:Int = Int()  
51         for scalar in charAt(num).unicodeScalars  
52         {  
53             number = Int(scalar.value)  
54         }  
55         return number  
56     }
57 }

8ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3         let dict:[Character: [String]] = 
 4         [
 5             "2": ["a", "b", "c"],
 6             "3": ["d", "e", "f"],
 7             "4": ["g", "h", "i"],
 8             "5": ["j", "k", "l"],
 9             "6": ["m", "n", "o"],
10             "7": ["p", "q", "r", "s"],
11             "8": ["t", "u", "v"],
12             "9": ["w", "x", "y", "z"],
13             
14         ]
15         if digits.isEmpty{
16             return [String]()
17         }
18         if digits.count == 1{
19             return dict[Character(digits)]!
20         }
21         var nextComb = letterCombinations(String(digits.dropFirst()))
22         var current = dict[digits[digits.startIndex]]!
23         var result = [String]()
24         for c in current{
25             for i in 0..<nextComb.count{
26                 result.append(String(c) + nextComb[i])
27             }
28         }
29         return result
30     }
31 }

12ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3         if digits.isEmpty == true {
 4             return []
 5         }
 6         
 7         var result: [String] = []
 8         // let chars = digits.characters
 9         let hash: [String: [String]] = ["2": ["a", "b", "c"], 
10                                        "3": ["d", "e", "f"], 
11                                        "4": ["g", "h", "i"], 
12                                        "5": ["j", "k", "l"], 
13                                        "6": ["m", "n", "o"], 
14                                        "7": ["p", "q", "r", "s"], 
15                                        "8": ["t", "u", "v"], 
16                                        "9": ["w", "x", "y", "z"]]
17                       
18         letterCombinationsHelper(digits, hash, &result, "")
19         
20         return result
21     }
22         
23     func letterCombinationsHelper(_ chars: String, 
24                                    _ hash: [String: [String]], 
25                                   _ result: inout [String], _ current: String) {
26         let count = chars.count
27         if count == 0 {
28             result.append(current)
29             return
30         }
31         
32         let sub = String(chars[chars.index(chars.startIndex, offsetBy: 0)])
33         let newList = hash[sub] ?? []
34         for item in newList {
35             if count >= 1 {
36                 let suubbb = String(chars[chars.index(chars.startIndex, offsetBy: 1)...])
37                 letterCombinationsHelper(suubbb, hash, &result, current + item)
38             } else {
39                 letterCombinationsHelper("", hash, &result, current + item)    
40             }
41             
42         }
43     }
44 }

16ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3         var combinations = [String](), combination = ""
 4         dfs(creatBoard(), &combinations, &combination, Array(digits), 0)
 5         return combinations
 6     }
 7     
 8     fileprivate func dfs(_ board: [String], _ combinations: inout [String], _ combination: inout String, _ digits: [Character], _ index: Int) {
 9         if digits.count == index {
10             if combination != "" {
11                 combinations.append(String(combination))
12             }
13             
14             return
15         }
16         
17         let digitStr = board[Int(String(digits[index]))!]
18         for digitChar in digitStr {
19             combination.append(digitChar)
20             dfs(board, &combinations, &combination, digits, index + 1)
21             combination.removeLast()
22         }
23     }
24     
25     
26     fileprivate func creatBoard() -> [String] {
27         var res = [String]()
28         
29         res.append("")
30         res.append("")
31         res.append("abc")
32         res.append("def")
33         res.append("ghi")
34         res.append("jkl")
35         res.append("mno")
36         res.append("pqrs")
37         res.append("tuv")
38         res.append("wxyz")
39         
40         return res
41     }
42 }

 16ms

 1 class Solution {
 2     private let keys = [" ", "*", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
 3     
 4     func letterCombinations(_ digits: String) -> [String] {
 5        
 6         if digits.count == 0 {
 7             return []
 8         }
 9         
10         var answer = [String]()
11         
12         let number = Array(digits)
13         
14         addCombinations(number, 0, &answer, "")
15         
16         return answer
17     }
18     
19     
20     func addCombinations(_ number: [Character], _ n: Int, _ answer: inout [String], _ char: String) {
21         
22         //base case when we reach the end of the key number letters
23         if n >= number.count {
24             //add this to the answe
25             answer.append(char)
26             return
27         }
28         
29         let digit = Int(String(number[n]))
30         
31         let key = keys[digit!]
32       
33         for k in key {
34 
35             addCombinations(number, n + 1, &answer, char + String(k))
36         }
37     }
38 }

20ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3 
 4         if digits.count == 0 {
 5             return []
 6         }
 7         let dic:[Character:String] = ["2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"]
 8         var res = [String]()
 9         var path = [Character]()
10         let digits = Array(digits)
11         dfs(&res,&path,dic,digits,0)
12 
13         return res
14     }
15 
16     func dfs(_ res:inout [String], _ path: inout [Character], _ dic:[Character:String], _ digits: [Character], _ idx:Int) {
17         if path.count == digits.count {
18             res.append(String(path))
19             return
20         }
21 
22         if idx < digits.count {
23             if let letters = dic[digits[idx]] {
24                 let chars = Array(letters)
25 
26                 for j in 0 ..< chars.count {
27                     path.append(chars[j])
28                     dfs(&res,&path,dic,digits,idx+1)
29                     path.removeLast()
30                 }
31             }
32         }
33     }
34 }

20ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3         var combinations = [String](), combination = ""
 4         
 5         dfs(createBoard(), &combinations, &combination, Array(digits), 0)
 6         
 7         return combinations
 8     }
 9     
10     fileprivate func createBoard() -> [String] {
11         var res = [String]()
12   
13         res.append("")
14         res.append("")
15         res.append("abc")
16         res.append("def")
17         res.append("ghi")
18         res.append("jkl")
19         res.append("mno")
20         res.append("pqrs")
21         res.append("tuv")
22         res.append("wxyz")
23   
24         return res
25     }
26     
27     fileprivate func dfs(_ board: [String], _ combinations: inout [String], _ combination: inout String, _ digits: [Character], _ index: Int) {
28         if digits.count == index {
29             if combination != "" {
30                 combinations.append(String(combination))
31             }
32             
33             return
34         }
35         
36         let digitStr = board[Int(String(digits[index]))!]
37         
38         for digitChar in digitStr {
39             combination.append(digitChar)
40             dfs(board, &combinations, &combination, digits, index + 1)
41             combination.removeLast()
42         }
43     }
44 }

24ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3          var result = [String]()
 4         let map:[Character:String] = ["2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"]
 5         var arr = [String]()
 6         for c in digits {
 7             arr.append(map[c]!)
 8         }
 9         var count = 0
10         for ss in arr {
11             var resulta = [String]()
12             for c in ss{
13                 if count == 0{
14                     result.append(String(c))
15                     resulta.append(String(c))
16 
17                 }else{
18                     for item in result{
19                         var i = item
20                         i.append(c)
21                         resulta.append(i)
22                     }
23                     
24                 }
25             }
26             result.removeAll()
27             result = resulta
28             count += 1
29         }
30         return result
31     }
32 }

28ms

 1 class Solution {
 2     
 3     var res = [String]()
 4     
 5     let w = [[],[],["a","b","c"],["d","e","f"],
 6                   ["g","h","i"],["j","k","l"],["m","n","o"],
 7                   ["p","q","r","s"],["t","u","v"],["w","x","y","z"]]
 8     
 9     func letterCombinations(_ digits: String) -> [String] {
10         var digitsArray = [String]()
11         for c in digits{
12             digitsArray.append(String(c))
13         }
14         dps(digitsArray,"")
15         return res
16     }
17     
18     func dps(_ least:[String],_ word:String) {
19         if least.count == 0{
20             if word.count != 0{
21                 res.append(word)
22             }
23             return
24         }
25         let c = Int(least[0])
26         let arr = w[c!]
27         var newLeast = least
28         newLeast.remove(at:0)
29         for c in arr{
30             dps(newLeast, word+c)
31         }
32     } 
33 }

40ms

 1 class Solution {
 2     func letterCombinations(_ digits: String) -> [String] {
 3         var results: [String] = [];
 4         
 5         func boundary(_ index: Int) -> (start: Int,end: Int) {
 6             if index == 2 {
 7                 return (97,99)
 8             }
 9             let result = boundary(index - 1)
10             var add_number = 3
11             if index == 7 || index == 9 {
12                 add_number = 4;
13             }
14             return (result.end + 1,result.end + add_number)
15         }
16         
17         var startIndex = digits.startIndex
18         while startIndex != digits.endIndex {
19             let endIndex = digits.index(startIndex, offsetBy: 1);
20             
21             let number = Int(digits[startIndex..<endIndex]);
22             let index_boundary = boundary(number!);
23             if results.isEmpty {
24                 for i in index_boundary.start...index_boundary.end {
25                     results.append(String(Character( UnicodeScalar.init(i)!)))
26                 }
27             }else {
28                 for str in results {
29                     for i in index_boundary.start...index_boundary.end {
30                         results.append(str.appending(String(Character( UnicodeScalar.init(i)!))))
31                     }
32                 }
33             }
34             startIndex = endIndex;
35         }
36         
37         return results.filter({
38              $0.count == digits.count
39         });
40     }
41 }

 

posted @ 2018-11-01 11:16  为敢技术  阅读(705)  评论(0编辑  收藏  举报