[LeetCode] 301. Remove Invalid Parentheses
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 301. Remove Invalid Parentheses相关的知识,希望对你有一定的参考价值。
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())()"] ")(" -> [""]
Credits:
Special thanks to @hpplayer for adding this problem and creating all test cases.
class Solution { public List<String> removeInvalidParentheses(String s) { Queue<String> queue = new LinkedList<>(); List<String> result = new ArrayList<>(); Set<String> visited = new HashSet<>(); visited.add(s); queue.offer(s); while(!queue.isEmpty()) { String tmp = queue.poll(); if (isValid(tmp)) { result.add(tmp); continue; } if (result.size() != 0 && tmp.length() <= result.get(0).length()) { continue; } for (int i = 0; i < tmp.length(); i++) { if (tmp.charAt(i) != ‘(‘ && tmp.charAt(i) != ‘)‘) { continue; } String newTmp = tmp.substring(0, i) + tmp.substring(i + 1, tmp.length()); if (visited.contains(newTmp)) { continue; } visited.add(newTmp); queue.offer(newTmp); } } return result; } private boolean isValid(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ‘(‘) { count++; } if (s.charAt(i) == ‘)‘) { if (count <= 0) { return false; } count--; } } return count == 0; } }
Failed case: remove the minimum number
Input:
"()())()"
Output:
["(())()","()()()","()()","(())","()",""]
Expected:
["(())()","()()()"]
Failed case: remove parentheses only
Input:
"x("
Output:
["x",""]
Expected:
["x"]
以上是关于[LeetCode] 301. Remove Invalid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 301. Remove Invalid Parentheses
leetcode 301-Remove Invalid Parentheses(hard)
[leetcode]301. Remove Invalid Parentheses 去除无效括号
[LeetCode] 301. Remove Invalid Parentheses 移除非法括号