中级农民
- 积分
- 110
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-28
- 最后登录
- 1970-1-1
|
附上301的最优解,欢迎小伙伴体验这个题的酸爽。
Key Points:
1. Generate unique answer once and only once, do not rely on Set.
2. Do not need preprocess.
3. Runtime 3 ms.
Explanation:
We all know how to check a string of parentheses is valid using a stack. Or even simpler use a counter.
The counter will increase when it is ‘(‘ and decrease when it is ‘)’. Whenever the counter is negative, we have more ‘)’ than ‘(‘ in the prefix.
To make the prefix valid, we need to remove a ‘)’. The problem is: which one? The answer is any one in the prefix. However, if we remove any one, we will generate duplicate results, for example: s = ()), we can remove s[1] or s[2] but the result is the same (). Thus, we restrict ourself to remove the first ) in a series of concecutive )s.
After the removal, the prefix is then valid. We then call the function recursively to solve the rest of the string. However, we need to keep another information: the last removal position. If we do not have this position, we will generate duplicate by removing two ‘)’ in two steps only with a different order.
For this, we keep tracking the last removal position and only remove ‘)’ after that.
Now one may ask. What about ‘(‘? What if s = ‘(()(()’ in which we need remove ‘(‘?
The answer is: do the same from right to left.
However a cleverer idea is: reverse the string and reuse the code!
Here is the final implement in Java.private static final char[] PAR = new char[]{'(', ')'};
private static final char[] REV_PAR = new char[]{ ')', '('};
private void remove(String s, List<String>ans, int last_i, int last_j, char[] par){
int stack = 0, i = last_i, j = last_j;
for(; i < s.length(); ++i){
if(s.charAt(i) == par[0]) stack++;
if(s.charAt(i) == par[1]) stack--;
if(stack >= 0) continue;
for(; j <= i; ++j){
if(s.charAt(j) != par[1]) continue;
if(j == last_j || s.charAt(j - 1) != par[1]) remove(s.substring(0, j) + s.substring(j + 1), ans, i, j, par);
}
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if(par[0] == PAR[0]) remove(reversed, ans, 0, 0, REV_PAR);
else ans.add(reversed);
}
public List<String> removeInvalidParentheses(String s) {
List<String> ans = new ArrayList<>();
remove(s, ans, 0, 0, PAR);
return ans;
}
|
|