Created
September 16, 2020 10:39
-
-
Save charlieInDen/692fa472d80aa7c6cc6ac07e1f02543d to your computer and use it in GitHub Desktop.
letterCombinations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
var hashMap: [String: String] = ["2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"] | |
func generateCombination(result: String, nextDigit: String, output: inout [String]) { | |
if nextDigit.isEmpty { | |
output.append(result) | |
return | |
}else { | |
var newDigit = nextDigit | |
let firstString = newDigit.removeFirst() | |
if let value = hashMap[String(firstString)] { | |
let letters = Array(value) | |
for letter in letters { | |
generateCombination(result: result + String(letter), nextDigit: newDigit, output: &output) | |
} | |
} | |
} | |
} | |
func letterCombinations(_ digits: String) -> [String] { | |
var output: [String] = [] | |
if digits.isEmpty == false { | |
generateCombination(result: "", nextDigit: digits, output: &output) | |
} | |
return output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment