Skip to content

Commit 18150be

Browse files
committed
Add week 6 solutions: valid-parentheses
1 parent 193f10b commit 18150be

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

valid-parentheses/gitsunmin.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* https://leetcode.com/problems/valid-parentheses/
3+
* time complexity : O(n)
4+
* space complexity : O(n)
5+
*/
6+
7+
type OpeningBracket = '(' | '[' | '{';
8+
type ClosingBracket = ')' | ']' | '}';
9+
10+
const isEmpty = (stack: OpeningBracket[]): boolean => stack.length === 0;
11+
12+
function isValid(s: string): boolean {
13+
const m = new Map<string, ClosingBracket>([
14+
['(', ')'],
15+
['[', ']'],
16+
['{', '}']
17+
]);
18+
const stack: OpeningBracket[] = [];
19+
20+
for (const c of s) {
21+
if (m.has(c)) stack.push(c as OpeningBracket);
22+
else if (isEmpty(stack) || c !== m.get(stack.pop() as OpeningBracket)) return false;
23+
}
24+
return isEmpty(stack);
25+
};

0 commit comments

Comments
 (0)