Skip to content

Commit 32fc22f

Browse files
committed
add solution : 20. Valid Parentheses
1 parent 4039896 commit 32fc22f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
*@link https://leetcode.com/problems/valid-parentheses/description/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - ๋‹ซํžŒ ๊ด„ํ˜ธ ๋‚˜์™”์„ ๋•Œ ์—ด๋ฆฐ ๊ด„ํ˜ธ์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’๊ณผ ์ง์ด ๋งž๋Š”์ง€ ์ฐพ์•„์•ผ๋˜๋‹ˆ๊นŒ stack ์‚ฌ์šฉ
6+
*
7+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
8+
* - ๋ฌธ์ž์—ด ์ˆœํšŒํ•˜๋ฉด์„œ ๊ด„ํ˜ธ์ฒดํฌํ•˜๋‹ˆ๊นŒ O(n)
9+
*
10+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(k)
11+
* - pairs ๊ฐ์ฒด ๊ณ ์ •๋œ ํฌ๊ธฐ๋กœ ์ €์žฅ O(1)
12+
* - stack์— ์—ด๋ฆฐ ๊ด„ํ˜ธ ๊ฐœ์ˆ˜๋งŒํผ ๋‹ด๊ธฐ๋‹ˆ๊นŒ O(k)
13+
*/
14+
15+
function isValid(s: string): boolean {
16+
const pairs: Record<string, string> = {
17+
")": "(",
18+
"}": "{",
19+
"]": "[",
20+
};
21+
const stack: string[] = [];
22+
23+
for (const char of s) {
24+
// ๋‹ซ๋Š” ๊ด„ํ˜ธ ๋‚˜์˜จ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ
25+
if (pairs[char]) {
26+
// ์ง์ด ๋งž์ง€ ์•Š๋Š” ๊ฒฝ์šฐ
27+
if (stack[stack.length - 1] !== pairs[char]) return false;
28+
29+
// ์ง์ด ๋งž๋Š” ๊ฒฝ์šฐ
30+
stack.pop();
31+
} else {
32+
// ์—ด๋ฆฐ ๊ด„ํ˜ธ๋Š” ๋ฐ”๋กœ stack์— ์ €์žฅ
33+
stack.push(char);
34+
}
35+
}
36+
37+
return stack.length === 0;
38+
}

0 commit comments

Comments
ย (0)