generated from shkvik/nodejs-console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-invalid-parentheses.ts
68 lines (59 loc) · 1.54 KB
/
remove-invalid-parentheses.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function removeInvalidParentheses(s: string): string[] {
const isValid = (str: string): boolean => {
let count = 0;
for (let char of str) {
if (char === '(') count++;
if (char === ')') count--;
if (count < 0) return false;
}
return count === 0;
};
const result: string[] = [];
const queue = [s];
const visited = new Set<string>();
let found = false;
while (queue.length > 0) {
const current = queue.shift()!;
if (isValid(current)) {
result.push(current);
found = true;
}
if (found) continue;
for (let i = 0; i < current.length; i++) {
if (current[i] !== '(' && current[i] !== ')') continue;
const next = current.slice(0, i) + current.slice(i + 1);
if (!visited.has(next)) {
queue.push(next);
visited.add(next);
}
}
}
return result.length ? result : [""];
}
function removeInvalidParenthesesDBG(){
const tests = [
{
input: "()())()",
result: ["()()()", "(())()"]
},
{
input: "(a)())()",
result: ["(a)()()", "(a())()"]
},
{
input: ")(",
result: [""]
}
];
tests.forEach((test, index) => {
const result = removeInvalidParentheses(test.input);
const success = JSON.stringify(result.sort()) === JSON.stringify(test.result.sort());
if (success) {
console.log(`${index} success`);
} else {
console.log(`${index} fail`);
console.log(`expected ${JSON.stringify(test.result)}`);
console.log(`got ${JSON.stringify(result)}`);
}
});
}