Skip to content

Commit 8159530

Browse files
committed
feat: Add solution for valid-parentheses problem
1 parent 673066c commit 8159530

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

easy/valid-parentheses.test.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Problem: https://leetcode.com/problems/valid-parentheses/
2+
// Doc: https://leetcode.com/problems/valid-parentheses/solutions/5491623/efficient-solution-for-valid-parentheses/
3+
const isValid = (s: string): boolean => {
4+
const stack: string[] = [];
5+
6+
const parClosedMap = {
7+
')': '(',
8+
'}': '{',
9+
']': '[',
10+
};
11+
12+
for (let i = 0; i < s.length; i++) {
13+
const char = s[i];
14+
if (!(char in parClosedMap)) {
15+
stack.push(char);
16+
continue;
17+
}
18+
19+
const popped = stack.pop();
20+
if (!popped) return false;
21+
const opened = parClosedMap[char];
22+
if (popped !== opened) return false;
23+
}
24+
25+
return stack.length === 0;
26+
};
27+
28+
describe('Valid Parentheses', () => {
29+
it('should return true for valid parentheses', () => {
30+
expect(isValid('()')).toBe(true);
31+
expect(isValid('()[]{}')).toBe(true);
32+
expect(isValid('{[]}')).toBe(true);
33+
expect(isValid('([{}])')).toBe(true);
34+
});
35+
36+
it('should return false for invalid parentheses', () => {
37+
expect(isValid('(]')).toBe(false);
38+
expect(isValid('([)]')).toBe(false);
39+
expect(isValid('[')).toBe(false);
40+
expect(isValid(']')).toBe(false);
41+
});
42+
});

0 commit comments

Comments
 (0)