Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created September 16, 2020 10:39
Show Gist options
  • Save charlieInDen/692fa472d80aa7c6cc6ac07e1f02543d to your computer and use it in GitHub Desktop.
Save charlieInDen/692fa472d80aa7c6cc6ac07e1f02543d to your computer and use it in GitHub Desktop.
letterCombinations
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