A string S
represents a list of words.
Each letter in the word has 1 or more options. If there is one option, the letter is represented as is. If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}"
represents options ["a", "b", "c"]
.
For example, "{a,b,c}d{e,f}"
represents the list ["ade", "adf", "bde", "bdf", "cde", "cdf"]
.
Return all words that can be formed in this manner, in lexicographical order.
思路:iterative 的写法, 核心思想就是:找一对括号,然后string 分成 before + splits + after; 先处理一个括号的情况,然后push 进stack,继续重复; 截止条件就是 找不到括号了,就装入list;
class Solution {
public String[] expand(String S) {
Stack stack = new Stack();
stack.push(S);
List list = new ArrayList();
// 核心思想就是:找一对括号,然后string 分成 before + splits + after;
// 先处理一个括号的情况,然后push 进stack,继续重复;
// 截止条件就是 找不到括号了,就装入list;
while(!stack.isEmpty()) {
String curr = stack.pop();
int left = 0;
int right = 0;
// 找右边的 括号的时候,把左边的也找到;
while(right < curr.length() && curr.charAt(right) != '}') {
if(curr.charAt(right) == '{') {
left = right;
}
right++;
}
if(right == curr.length()) {
list.add(curr);
continue;
}
String before = curr.substring(0, left); // { 不要了;
String[] splits = curr.substring(left + 1, right).split(",");
String after = curr.substring(right + 1); // } 不要了;
for(String split: splits) {
String newstr = before + split + after;
stack.push(newstr);
}
}
Collections.sort(list);
String[] res = new String[list.size()];
int index = 0;
for(String word: list) {
res[index++] = word;
}
return res;
}
}
backtracking, 考点就是如何分割字符串,核心就是用index标记走到哪里了,然后把 {}找到,并且切出来split,然后for 循环做backtracking
class Solution {
public String[] expand(String S) {
List list = new ArrayList();
StringBuilder sb = new StringBuilder();
dfs(S, list, sb, 0);
Collections.sort(list);
String[] res = new String[list.size()];
return list.toArray(res);
}
private void dfs(String S, List list, StringBuilder sb, int index) {
if(index == S.length()) {
list.add(new String(sb.toString()));
return;
}
if(S.charAt(index) == '{') {
int r = index;
while(index < S.length() && S.charAt(r) != '}') {
r++;
}
String middle = S.substring(index + 1, r);
String[] splits = middle.split(",");
for(String split: splits) {
sb.append(split);
dfs(S, list, sb, r + 1); // 注意这里是 r + 1;
sb.setLength(sb.length() - split.length());
}
} else {
sb.append(S.charAt(index));
dfs(S, list, sb, index + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}