Skip to content

Commit cb3db2a

Browse files
committed
leetcode 17
1 parent 3ef6402 commit cb3db2a

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
- 14.Longest Common Prefix `easy` `string` [link](https://leetcode.com/problems/longest-common-prefix/description/) [code](./leetcode/14.js)
3434
- 15.3Sum `medium` `array` [link](https://leetcode.com/problems/3sum/) [code](./leetcode/15.js)
3535
- 16.3Sum Closest `medium` `array` [link](https://leetcode.com/problems/3sum-closest/) [code](./leetcode/16.js)
36+
- 17.Letter Combinations of a Phone Number `medium` `string` [link](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) [code](./leetcode/17.js)
3637

3738
## lintcode
3839

leetcode/17.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
17. Letter Combinations of a Phone Number
3+
4+
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
5+
6+
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
7+
8+
9+
10+
Example:
11+
12+
Input: "23"
13+
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
14+
15+
Note:
16+
Although the above answer is in lexicographical order, your answer could be in any order you want.
17+
*/
18+
19+
20+
/**
21+
* @param {string} digits
22+
* @return {string[]}
23+
*/
24+
var letterCombinations = function(digits) {
25+
const letterMap = {
26+
2: 'abc',
27+
3: 'def',
28+
4: 'ghi',
29+
5: 'jkl',
30+
6: 'mno',
31+
7: 'pqrs',
32+
8: 'tuv',
33+
9: 'wxyz',
34+
};
35+
36+
const nums = digits.split('');
37+
let res = [];
38+
39+
const len = nums.length;
40+
if (!len) return res;
41+
if (len <= 1) {
42+
return letterMap[nums[0]].split('');
43+
}
44+
45+
let arr1 = letterCombinations(digits.substring(0, 1));
46+
let arr2 = letterCombinations(digits.substring(1));
47+
48+
for (let i = 0; i < arr1.length; i++) {
49+
for (let j = 0; j < arr2.length; j++) {
50+
res.push(arr1[i] + arr2[j]);
51+
}
52+
}
53+
54+
return res;
55+
};

0 commit comments

Comments
 (0)