-
Notifications
You must be signed in to change notification settings - Fork 0
/
17.letter-combinations-of-a-phone-number.js
81 lines (80 loc) · 1.77 KB
/
17.letter-combinations-of-a-phone-number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* @lc app=leetcode id=17 lang=javascript
*
* [17] Letter Combinations of a Phone Number
*
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
*
* algorithms
* Medium (48.02%)
* Likes: 4785
* Dislikes: 458
* Total Accepted: 702.5K
* Total Submissions: 1.5M
* Testcase Example: '"23"'
*
* Given a string containing digits from 2-9 inclusive, return all possible
* letter combinations that the number could represent. Return the answer in
* any order.
*
* A mapping of digit to letters (just like on the telephone buttons) is given
* below. Note that 1 does not map to any letters.
*
*
*
*
* Example 1:
*
*
* Input: digits = "23"
* Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
*
*
* Example 2:
*
*
* Input: digits = ""
* Output: []
*
*
* Example 3:
*
*
* Input: digits = "2"
* Output: ["a","b","c"]
*
*
*
* Constraints:
*
*
* 0 <= digits.length <= 4
* digits[i] is a digit in the range ['2', '9'].
*
*
*/
// @lc code=start
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
let map = { 2: ["a", "b", "c"], 3: ["d", "e", "f"], 4: ["g", "h", "i"], 5: ["j", "k", "l"], 6: ["m", "n", "o"], 7: ["p", "q", "r", "s"], 8: ["t", "u", "v"], 9: ["w", "x", "y", "z"] };
let results = [];
for (let i = 0; i < digits.length; i++) {
const tempChar = digits.charAt(i);
if (results.length === 0) results = results.concat(map[tempChar]);
else {
const length = results.length;
for (let j = 0; j < length; j++) {
const letters = map[tempChar];
const str = results.shift(0);
for (let k = 0; k < letters.length; k++) {
results.push(str + letters[k]);
}
}
}
}
return results;
};
// @lc code=end