2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_301.java 1.60 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.interview.top_interview_questions.hard_collection.backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* 301. Remove Invalid Parentheses
* <p>
* Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
* <p>
* Note: The input string may contain letters other than the parentheses ( and ).
* <p>
* Example 1:
* <p>
* Input: "()())()"
* Output: ["()()()", "(())()"]
* <p>
* Example 2:
* <p>
* Input: "(a)())()"
* Output: ["(a)()()", "(a())()"]
* <p>
* Example 3:
* <p>
* Input: ")("
* Output: [""]
*/
public class _301 {
public List<String> removeInvalidParentheses(String s) {
List<String> ans = new ArrayList<>();
remove(s, ans, 0, 0, new char[]{'(', ')'});
return ans;
}
private void remove(String s, List<String> ans, int last_i, int last_j, char[] par) {
for (int stack = 0, i = last_i; i < s.length(); ++i) {
if (s.charAt(i) == par[0]) stack++;
if (s.charAt(i) == par[1]) stack--;
if (stack >= 0) continue;
for (int j = last_j; j <= i; ++j)
if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1]))
remove(s.substring(0, j) + s.substring(j + 1, s.length()), ans, i, j, par);
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (par[0] == '(') // finished left to right
remove(reversed, ans, 0, 0, new char[]{')', '('});
else // finished right to left
ans.add(reversed);
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助