Skip to content

Commit 7afa66f

Browse files
authored
Create 301-remove-invalid-parentheses.js
1 parent 0e52997 commit 7afa66f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

301-remove-invalid-parentheses.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {string} s
3+
* @return {string[]}
4+
*/
5+
const removeInvalidParentheses = function(s) {
6+
const ans = [];
7+
remove(s, ans, 0, 0, ["(", ")"]);
8+
return ans;
9+
};
10+
11+
function remove(s, ans, last_i, last_j, par) {
12+
for (let stack = 0, i = last_i; i < s.length; i++) {
13+
if (s.charAt(i) === par[0]) stack++;
14+
if (s.charAt(i) === par[1]) stack--;
15+
if (stack >= 0) continue;
16+
for (let j = last_j; j <= i; j++) {
17+
if (
18+
s.charAt(j) === par[1] &&
19+
(j === last_j || s.charAt(j - 1) != par[1])
20+
) {
21+
remove(s.slice(0, j) + s.slice(j + 1), ans, i, j, par);
22+
}
23+
}
24+
return;
25+
}
26+
const reversed = s
27+
.split("")
28+
.reverse()
29+
.join("");
30+
if (par[0] === "(") {
31+
remove(reversed, ans, 0, 0, [")", "("]);
32+
} else {
33+
ans.push(reversed);
34+
}
35+
}

0 commit comments

Comments
 (0)