LeetCode Remove Invalid Parentheses
来源:互联网 发布:提高口才知乎 编辑:程序博客网 时间:2024/05/21 08:44
Description:
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses (
and )
.
Examples:
"()())()" -> ["()()()", "(())()"]"(a)())()" -> ["(a)()()", "(a())()"]")(" -> [""]
Solution:
先用一次Stack算出最少需要移去的括号数量
然后用DFS求出所有可能的String
注:这道题目还是那个问题,没有给我们String的范围,很难判断用什么方法……
<span style="font-size:18px;">import java.util.*;public class Solution {HashSet<String> set = new HashSet<>();List<String> list;public List<String> removeInvalidParentheses(String s) {int n = s.length();int validNum = getValidNum(s);int removeNum = n - validNum;dfs(0, removeNum, s, "");list = new ArrayList<String>(set);return list;}public int getValidNum(String s) {int num = 0;Stack<Character> stack = new Stack<Character>();for (int i = 0; i < s.length(); i++) {char ch = s.charAt(i);if (ch == '(') {stack.add(ch);} else if (ch == ')') {if (!stack.isEmpty()) {stack.pop();num += 2;}} elsenum++;}return num;}public void dfs(int tot, int removeNum, String str, String neoStr) {if (removeNum == 0) {neoStr = neoStr + str.substring(tot, str.length());if (valid(neoStr))set.add(neoStr);return;}for (int i = tot; i < str.length() - removeNum + 1; i++) {char ch = str.charAt(i);if (ch != '(' && ch != ')')continue;dfs(i + 1, removeNum - 1, str, neoStr + str.substring(tot, i));}}boolean valid(String s) {Stack<Character> stack = new Stack<Character>();for (int i = 0; i < s.length(); i++) {char ch = s.charAt(i);if (ch == '(')stack.add(ch);else if (ch == ')') {if (stack.isEmpty())return false;stack.pop();}}return stack.isEmpty();}}</span>
0 0
- [LeetCode] Remove Invalid Parentheses
- LeetCode -- Remove Invalid Parentheses
- leetcode Remove Invalid Parentheses
- LeetCode Remove Invalid Parentheses
- [Leetcode]Remove Invalid Parentheses
- leetcode:Remove Invalid Parentheses
- leetcode - Remove Invalid Parentheses
- 【Leetcode】Remove Invalid Parentheses
- LeetCode:Remove Invalid Parentheses
- Remove Invalid Parentheses -- Leetcode
- [LeetCode]Remove Invalid Parentheses
- leetcode 301 : Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- leetcode 301. Remove Invalid Parentheses
- [leetcode] 301. Remove Invalid Parentheses
- leetcode.301. Remove Invalid Parentheses
- [LeetCode]--301. Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- ES6学习——类语法:继承内置的类(如Array,Error等)
- python isinstance(), stack,判断list, dict, tuple为空
- 对Keil MDK 启动代码的理解
- linux(Ubuntu)中安装mavne私服Nexus
- Android 进程生命周期 Process Lifecycle
- LeetCode Remove Invalid Parentheses
- Excel中的Array Formula
- LeetCode Additive Number
- C++的高级用法
- Swift学习之可选类型Optional
- bzoj2243: [SDOI2011]染色
- 微信公众号开发(一):搭建开发环境
- 微信公众号开发(二):利用责任链和模板方法模式设计消息的处理流程
- Linux找出程序启动失败的原因