Imports System
Imports System.Collections.Generic
' Letter Combinations of a Phone Number
' Given a string containing digits from 2-9,
' get all possible letter combinations that a phone number represents
Class Program
Private letters As List(Of String) = New List(Of String) From {
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
}
Private result As List(Of String) = New List(Of String)()
Private Sub Print(ByVal lst As List(Of String))
For Each n As String In lst
Console.Write(n & " ")
Next
Console.WriteLine()
End Sub
Private Sub CreateCombinations(ByVal digits As String, ByVal output As String, ByVal di As Integer)
If digits.Length = di Then
result.Add(output)
Return
End If
' Use Convert.ToByte to get the ASCII value of the character and calculate the index
Dim index As Integer = Convert.ToByte(digits(di)) - Convert.ToByte("2"c)
For i As Integer = 0 To letters(index).Length - 1
output += letters(index)(i)
CreateCombinations(digits, output, di + 1)
output = output.Substring(0, output.Length - 1)
Next
End Sub
Private Function LetterCombinationsOfPhoneNumber(ByVal digits As String) As List(Of String)
If digits = "" Then
Return result
End If
Dim output As String = ""
CreateCombinations(digits, output, 0)
Return result
End Function
Public Shared Sub Main(ByVal args As String())
Dim p As Program = New Program()
Dim result As List(Of String) = p.LetterCombinationsOfPhoneNumber("23")
p.Print(result)
End Sub
End Class
' run:
'
' ad ae af bd be bf cd ce cf
'