Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f8d1281

Browse files
committed
solved: Letter combinations of a phone number
1 parent fb2902f commit f8d1281

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
- [Text Justification](#text-justification)
2626
- [3 Sum](#3-sum)
2727
- [3 Sum Closest](#3-sum-closest)
28+
- [Letter combinations of a phone number](#letter-combinations-of-a-phone-number)
2829

2930
### String to Int - Atoi
3031

@@ -676,4 +677,46 @@ int threeSumClosest(List<int> nums, int target) {
676677
677678
return result;
678679
}
680+
```
681+
682+
### Letter combinations of a phone number
683+
684+
```dart
685+
const Map<int, List<String>> chars = {
686+
2: ['a', 'b', 'c'],
687+
3: ['d', 'e', 'f'],
688+
4: ['g', 'h', 'i'],
689+
5: ['k', 'j', 'l'],
690+
6: ['m', 'n', 'o'],
691+
7: ['p', 'q', 'r', 's'],
692+
8: ['t', 'u', 'v'],
693+
9: ['w', 'x', 'y', 'z'],
694+
};
695+
696+
List<String> letterCombinations(String digits) {
697+
if (digits.isEmpty) return [];
698+
699+
final List<String> result = [];
700+
701+
lookupChar(0, "", digits.length, digits, result);
702+
703+
return result;
704+
}
705+
706+
void lookupChar(
707+
int index,
708+
String res,
709+
int length,
710+
String digits,
711+
List<String> result,
712+
) {
713+
if (index == digits.length)
714+
result.add(res);
715+
else {
716+
final List<String> letters = chars[int.parse(digits[index])]!;
717+
for (int i = 0; i < letters.length; i++) {
718+
lookupChar(index + 1, res + letters[i], length, digits, result);
719+
}
720+
}
721+
}
679722
```
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
void main(List<String> args) {
2+
List<String> cases = ["23", "", "2", "9"];
3+
4+
for (final testcase in cases) {
5+
print(letterCombinations(testcase));
6+
}
7+
}
8+
9+
const Map<int, List<String>> chars = {
10+
2: ['a', 'b', 'c'],
11+
3: ['d', 'e', 'f'],
12+
4: ['g', 'h', 'i'],
13+
5: ['k', 'j', 'l'],
14+
6: ['m', 'n', 'o'],
15+
7: ['p', 'q', 'r', 's'],
16+
8: ['t', 'u', 'v'],
17+
9: ['w', 'x', 'y', 'z'],
18+
};
19+
20+
List<String> letterCombinations(String digits) {
21+
if (digits.isEmpty) return [];
22+
23+
final List<String> result = [];
24+
25+
lookupChar(0, "", digits.length, digits, result);
26+
27+
return result;
28+
}
29+
30+
void lookupChar(
31+
int index,
32+
String res,
33+
int length,
34+
String digits,
35+
List<String> result,
36+
) {
37+
if (index == digits.length)
38+
result.add(res);
39+
else {
40+
final List<String> letters = chars[int.parse(digits[index])]!;
41+
for (int i = 0; i < letters.length; i++) {
42+
lookupChar(index + 1, res + letters[i], length, digits, result);
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)