Skip to content

Commit f62d18b

Browse files
committed
Leetcode | Letter Combinations of a Phone Number | Java
1 parent 1863f5d commit f62d18b

3 files changed

Lines changed: 82 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: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.devstromo.medium.p17;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Map;
6+
7+
public class Solution {
8+
private static final Map<Character, String> phoneMap = Map.of(
9+
'2', "abc", '3', "def",
10+
'4', "ghi", '5', "jkl", '6', "mno",
11+
'7', "pqrs", '8', "tuv", '9', "wxyz"
12+
);
13+
14+
public List<String> letterCombinations(String digits) {
15+
List<String> result = new ArrayList<>();
16+
if (digits == null || digits.isEmpty()) return result;
17+
backtrack(digits, 0, new StringBuilder(), result);
18+
return result;
19+
}
20+
21+
private void backtrack(String digits, int index, StringBuilder path, List<String> result) {
22+
if (index == digits.length()) {
23+
result.add(path.toString());
24+
return;
25+
}
26+
27+
String possibleLetters = phoneMap.get(digits.charAt(index));
28+
for (char c : possibleLetters.toCharArray()) {
29+
path.append(c);
30+
backtrack(digits, index + 1, path, result);
31+
path.deleteCharAt(path.length() - 1); // backtrack
32+
}
33+
}
34+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.devstromo.medium.p17;
2+
3+
import org.junit.jupiter.api.DisplayName;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.List;
7+
8+
import static org.junit.jupiter.api.Assertions.*;
9+
10+
class SolutionUnitTest {
11+
private final Solution solution = new Solution();
12+
13+
@Test
14+
@DisplayName("Letter Combinations of a Phone Number")
15+
void letterCombinations() {
16+
assertEquals(List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"), solution.letterCombinations("23"));
17+
assertEquals(List.of(), solution.letterCombinations(""));
18+
assertEquals(List.of("a", "b", "c"), solution.letterCombinations("2"));
19+
}
20+
21+
}

0 commit comments

Comments
 (0)