-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1087. Brace Expansion.java
43 lines (36 loc) · 1.21 KB
/
1087. Brace Expansion.java
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
https://leetcode.com/problems/brace-expansion/
思路:Backtracking
时间复杂度:
空间复杂度:
class Solution {
private void dfs(String S, int index, StringBuilder sb, List<String> res) {
if (index == S.length()) {
res.add(sb.toString());
return;
}
if (S.charAt(index) == '{') {
int right = S.indexOf('}', index + 1);
for (char c : S.substring(index + 1, right).toCharArray()) {
if (c == ',') continue;
sb.append(c);
dfs(S, right + 1, sb, res);
sb.deleteCharAt(sb.length() - 1);
}
} else {
int right = S.indexOf('{', index);
if (right < 0) {
right = S.length();
}
String substr = S.substring(index, right);
sb.append(substr);
dfs(S, right, sb, res);
sb.delete(sb.length() - substr.length(), sb.length());
}
}
public String[] expand(String S) {
List<String> res = new ArrayList<>();
dfs(S, 0, new StringBuilder(), res);
Collections.sort(res);
return res.toArray(new String[0]);
}
}