Skip to content

Commit db8159c

Browse files
committed
Add solution #17
1 parent bdcab53 commit db8159c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium|
1515
10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard|
1616
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
17+
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
1718
27|[Remove Element](./0027-remove-element.js)|Easy|
1819
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1920
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 17. Letter Combinations of a Phone Number
3+
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/
4+
* Difficulty: Medium
5+
*
6+
* Given a string containing digits from 2-9 inclusive, return all possible
7+
* letter combinations that the number could represent. Return the answer
8+
* in any order.
9+
*
10+
* A mapping of digit to letters (just like on the telephone buttons) is
11+
* given below. Note that 1 does not map to any letters.
12+
*/
13+
14+
/**
15+
* @param {string} digits
16+
* @return {string[]}
17+
*/
18+
var letterCombinations = function(digits) {
19+
if (!digits || !digits.length) return [];
20+
21+
const map = {
22+
2: 'abc',
23+
3: 'def',
24+
4: 'ghi',
25+
5: 'jkl',
26+
6: 'mno',
27+
7: 'pqrs',
28+
8: 'tuv',
29+
9: 'wxyz'
30+
};
31+
32+
if (digits.length === 1) {
33+
return map[digits].split('');
34+
}
35+
36+
const result = [];
37+
const group1 = letterCombinations(digits.substr(0, 1));
38+
const group2 = letterCombinations(digits.substr(1));
39+
40+
for (let i = 0; i < group1.length; i++) {
41+
for (let j = 0; j < group2.length; j++) {
42+
result.push(group1[i] + group2[j]);
43+
}
44+
}
45+
46+
return result;
47+
};

0 commit comments

Comments
 (0)