Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Last active August 29, 2015 14:27
Show Gist options
  • Save aniruddha84/5730f08b4ec097678826 to your computer and use it in GitHub Desktop.
Save aniruddha84/5730f08b4ec097678826 to your computer and use it in GitHub Desktop.
Letter combinations Problem
# Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
# Given a digit string, return all possible letter combinations that the number could represent.
# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
@look_up = {
"2" => "abc",
"3" => "def",
"4" => "ghi",
"5" => "jkl",
"6" => "mno",
"7" => "pqrs",
"8" => "tuv",
"9" => "wxyz"
}
def get_letter_combinations(num_string)
num_string.gsub!(/[01]/, "")
if num_string.size == 1
return @look_up[num_string].chars
end
result = []
combinations = get_letter_combinations(num_string[1..-1])
@look_up[num_string[0]].chars.each do |c|
combinations.each do |cb|
result << (c + cb)
end
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment