Skip to content

Commit b066761

Browse files
author
Thuy Trinh
committed
Solution for "Letter Combinations of a Phone Number"
1 parent be64e3c commit b066761

File tree

3 files changed

+75
-1
lines changed

3 files changed

+75
-1
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
buildscript {
2-
ext.kotlinVersion = '1.1.60'
2+
ext.kotlinVersion = '1.2.0'
33

44
repositories {
55
mavenCentral()
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package leetcode.lettercombinations
2+
3+
import java.util.*
4+
5+
class Solution {
6+
private val kb = hashMapOf(
7+
'1' to "",
8+
'2' to "abc",
9+
'3' to "def",
10+
'4' to "ghi",
11+
'5' to "jkl",
12+
'6' to "mno",
13+
'7' to "pqrs",
14+
'8' to "tuv",
15+
'9' to "wxyz",
16+
'0' to ""
17+
)
18+
19+
fun letterCombinations(digits: String): List<String> {
20+
// "abc" and "def"
21+
// * Pick 'a'. Push 'a'.
22+
// * Pick 'd'. Push 'd'.
23+
// * Print stack. Pop stack.
24+
// * Pick 'e'. Push 'e'.
25+
// * Print stack. Pop stack.
26+
return when {
27+
digits.isEmpty() -> emptyList()
28+
else -> {
29+
val texts: List<String> = digits.map { kb[it] ?: "" }
30+
val result = mutableListOf<String>()
31+
generate(texts, 0, result, Stack())
32+
result
33+
}
34+
}
35+
}
36+
37+
private fun generate(
38+
texts: List<String>, // texts = ["abc", "def"]
39+
i: Int, // i = 2
40+
result: MutableList<String>, // result = []
41+
stack: Stack<Char> // stack = [a, e]
42+
) {
43+
when (i) { // i = 2
44+
texts.size -> { // size = 2
45+
// result = ["ad", "ae"]
46+
result += stack.joinToString(separator = "")
47+
}
48+
else -> texts[i].forEach {
49+
stack += it // it = 'f', stack = [a, f]
50+
generate(texts, i + 1, result, stack)
51+
stack.pop() // stack = [a]
52+
}
53+
}
54+
}
55+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package leetcode.lettercombinations
2+
3+
import org.amshove.kluent.shouldBeEmpty
4+
import org.amshove.kluent.shouldContainAll
5+
import org.junit.Test
6+
7+
class SolutionTest {
8+
@Test
9+
fun letterCombinations() {
10+
Solution()
11+
.letterCombinations("23")
12+
.shouldContainAll(listOf(
13+
"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"
14+
))
15+
Solution()
16+
.letterCombinations("01")
17+
.shouldBeEmpty()
18+
}
19+
}

0 commit comments

Comments
 (0)