-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombination.java
More file actions
51 lines (44 loc) · 1.37 KB
/
LetterCombination.java
File metadata and controls
51 lines (44 loc) · 1.37 KB
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
package Recursion;
import java.util.ArrayList;
import java.util.List;
public class LetterCombination {
private static void pad(String str, String ans) {
if (str.length() == 0) {
System.out.println(ans);
return;
}
int digit = str.charAt(0) - '0';
for (int i = (digit - 1) * 3; i < (digit * 3); i++) {
char ch = (char) ('a' + i);
pad(str.substring(1), ans + ch);
}
}
static List<String> padleetcode(String str, String ans) {
if (str.length() == 0) {
ArrayList<String> list = new ArrayList<>();
list.add(ans);
return list;
}
int digit = str.charAt(0) - '0';
ArrayList<String> mainlist = new ArrayList<>();
int s = (digit - 2) * 3, e = ((digit - 1) * 3);
if (digit == 7)
e += 1;
else if (digit == 8) {
s += 1;
e += 1;
} else if (digit == 9) {
s += 1;
e += 2;
}
for (int i = s; i < e; i++) {
char ch = (char) ('a' + i);
mainlist.addAll(padleetcode(str.substring(1), ans + ch));
}
return mainlist;
}
public static void main(String[] args) {
pad("18", ""); // 1-8 (9-yz)
System.out.println(padleetcode("29", "")); // 2-9 (7 - pqrs, 8 - tuv, 9 - wxyz)
}
}