One, foreword
I failed the first time because the array.propTotype. splice method changes the length of the original Array. Note my error here for next time.
2. Title Description
Forgive me for being lazy. I took a screenshot directly from Leetcode to see our title description. For a more clear description, please see the title link of Leetcode
Three, the analysis
- Find invalid parentheses removed
- How to find?
- Hit the left parenthesis and press delLeft
- If the size of the left parenthesis stack is greater than 0, exit the stack
- When a close parenthesis is encountered, the size of the open parenthesis stack is equal to 0, and the delRight stack is pushed
- The two stacks are then merged, which is the subscript record of all invalid parentheses
- To know the invalid location, just iterate over the delete
Four, code,
Git code link
/** * @param {string} s * @return {string} */ const minRemoveToMakeValid = function(s) {// Save the removed open parenthesis subscript const delLeft = [] // Save the deleted close bracket subscript const delRight = [] // Convert string to array const sArr = s.split(" ") // traverse character array for(let I = 0; i < sArr.length; I++) {if (sArr [I] = = = '(') {/ / meet left parenthesis, pumped delLeft delLeft. Push (I)} the if (sArr [I] = = =') ') {if (delLeft. Length) {/ / meet a right parenthesis, Delleft.pop ()} else {// Open parenthesis = 0, open parenthesis = 0, open parenthesis = 0, open parenthesis = 0 Const del = [...delLeft,...delRight] for(let I = 0; i < del.length; I ++) {// sarr.splice (del[I], 1) ------ SArr [del[I]] = "} return sarr.join (")};Copy the code