diff --git a/LeetcodeProblems/Remove_Invalid_Parentheses.js b/LeetcodeProblems/Remove_Invalid_Parentheses.js new file mode 100644 index 0000000..0788026 --- /dev/null +++ b/LeetcodeProblems/Remove_Invalid_Parentheses.js @@ -0,0 +1,79 @@ +/* +Remove Invalid Parentheses +https://leetcode.com/problems/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 ). + +Example 1: + +Input: "()())()" +Output: ["()()()", "(())()"] +Example 2: + +Input: "(a)())()" +Output: ["(a)()()", "(a())()"] +Example 3: + +Input: ")(" +Output: [""] +*/ + +/** + * @param {string} s + * @return {string[]} + */ +var removeInvalidParentheses = function(s) { + var queue = []; + var visited = new Set(); + queue.push(s); + var result = []; + var found = false; + + while(queue.length !== 0) { + var str = queue.shift(); + if(isValid(str)) { + result.push(str); + found = true; + } else if(!found){ + for(var i = 0; i < s.length; i++) { + if(str[i] === "(" || str[i] === ")") { + var subStr = str.slice(0, i) + str.slice(i + 1, s.length); + if(!visited.has(subStr)) { + queue.push(subStr); + visited.add(subStr); + } + } + } + } + } + + return result; +}; + +var isValid = function(s) { + var leftCount = 0; + var iter = 0; + while(iter < s.length) { + if(s[iter] === "(") + leftCount++; + else if(s[iter] === ")") { + leftCount--; + if(leftCount < 0) + return false; + } + iter++; + } + + return leftCount === 0; +} + +var main = function() { + console.log(removeInvalidParentheses("))))(()")); + console.log(removeInvalidParentheses("(()")); + console.log(removeInvalidParentheses("(d))()")); + console.log(removeInvalidParentheses("(())")) +} + +module.exports.main = main; \ No newline at end of file diff --git a/README.md b/README.md index f314b96..45430f9 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Solutions of algorithm problems using Javascript | Name | Level | Link | | - | - | - | | [Edit Distance ](/LeetcodeProblems/Edit_Distance.js) | Hard | https://leetcode.com/problems/edit-distance/ | +| [Remove Invalid Parentheses ](/LeetcodeProblems/Remove_Invalid_Parentheses.js) | Hard | https://leetcode.com/problems/remove-invalid-parentheses/ | | [Longest Consecutive Sequence ](/LeetcodeProblems/Longest_Consecutive_Sequence.js) | Hard | https://leetcode.com/problems/longest-consecutive-sequence/ | | [Minimum Window Substring ](/LeetcodeProblems/Minimum_Window_Substring.js) | Hard | https://leetcode.com/problems/minimum-window-substring/ | | [Regular Expression Matching ](/LeetcodeProblems/Regular_Expression_Matching.js) | Hard | https://leetcode.com/problems/regular-expression-matching/ |