Skip to content

Commit 3990510

Browse files
committed
Leetcode | Letter Combinations of a Phone Number | Kotlin
1 parent f62d18b commit 3990510

3 files changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# 17. Letter Combinations of a Phone Number
2+
3+
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could
4+
represent. Return the answer in any order.
5+
6+
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any
7+
letters.
8+
9+
Example 1:
10+
11+
Input: digits = "23"
12+
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
13+
14+
Example 2:
15+
16+
Input: digits = ""
17+
Output: []
18+
19+
Example 3:
20+
21+
Input: digits = "2"
22+
Output: ["a","b","c"]
23+
24+
Constraints:
25+
26+
- `0 <= digits.length <= 4`
27+
- `digits[i]` is a digit in the range `['2', '9']`.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.devstromo.medium.p17
2+
3+
class SolutionKt {
4+
private val phoneMap = mapOf(
5+
'2' to "abc", '3' to "def",
6+
'4' to "ghi", '5' to "jkl", '6' to "mno",
7+
'7' to "pqrs", '8' to "tuv", '9' to "wxyz"
8+
)
9+
10+
fun letterCombinations(digits: String): List<String> {
11+
if (digits.isEmpty()) return emptyList()
12+
val result = mutableListOf<String>()
13+
backtrack(digits, 0, StringBuilder(), result)
14+
return result
15+
}
16+
17+
private fun backtrack(
18+
digits: String,
19+
index: Int,
20+
path: StringBuilder,
21+
result: MutableList<String>
22+
) {
23+
if (index == digits.length) {
24+
result.add(path.toString())
25+
return
26+
}
27+
28+
val letters = phoneMap[digits[index]] ?: return
29+
for (c in letters) {
30+
path.append(c)
31+
backtrack(digits, index + 1, path, result)
32+
path.deleteCharAt(path.lastIndex)
33+
}
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.devstromo.medium.p17
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class SolutionKtUnitTest {
7+
private val solution = SolutionKt()
8+
9+
@Test
10+
fun `Test Letter Combinations of a Phone Number`() {
11+
assertEquals(
12+
listOf("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"),
13+
solution.letterCombinations("23")
14+
)
15+
assertEquals(listOf<String>(), solution.letterCombinations(""))
16+
assertEquals(listOf("a", "b", "c"), solution.letterCombinations("2"))
17+
}
18+
}

0 commit comments

Comments
 (0)