Skip to content

Commit 46d6fc9

Browse files
committed
1. Valid Parentheses
1 parent 189509b commit 46d6fc9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

โ€Žvalid-parentheses/whewchews.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* ์•„์ด๋””์–ด
3+
* stack ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•ด ์—ฌ๋Š” ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ค๋ฉด ์ˆœ์„œ๋Œ€๋กœ ์ €์žฅํ•ด๋‘”๋‹ค.
4+
* stack์„ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๋Š” ๊ฐ€์žฅ ์ตœ๊ทผ ์—ฌ๋Š” ๊ด„ํ˜ธ๊ฐ€ ์–ด๋–ค ๊ฒƒ์ธ์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•จ์ด๋‹ค.(๋งˆ์ง€๋ง‰์— ์‚ฝ์ž…ํ•œ ๊ฐ’์„ ๋จผ์ € ์‚ฌ์šฉํ•จ)
5+
* ๋‹ซ๋Š” ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ค๋ฉด stack์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์ด pair์ธ ์—ฌ๋Š” ๊ด„ํ˜ธ์ธ์ง€ ์ฒดํฌํ•œ๋‹ค. ๋‹ค๋ฅด๋ฉด return false
6+
* ๋ฌธ์ž์—ด ๋ฐ˜๋ณต๋ฌธ์„ ๋‹ค ๋Œ๊ณ  stack์— ์—ฌ๋Š” ๊ด„ํ˜ธ๊ฐ€ ๋‚จ์•„์žˆ์ง€ ์•Š์€์ง€ ๋ณธ๋‹ค. ๋‚จ์•„์žˆ์œผ๋ฉด return false
7+
* ์œ„์˜ ๋‘ ๊ฒฝ์šฐ์— ํ•ด๋‹น๋˜์ง€ ์•Š์œผ๋ฉด return true
8+
*/
9+
function isValid(s: string): boolean {
10+
const charSet = new Set(["(", "{", "["]);
11+
const openCharStack = [];
12+
const CHAR_PAIR = {
13+
"]": "[",
14+
"}": "{",
15+
")": "(",
16+
};
17+
18+
for (let i = 0; i <= s.length - 1; i++) {
19+
const char = s[i];
20+
if (charSet.has(char)) {
21+
openCharStack.push(char);
22+
continue;
23+
}
24+
25+
if (char in CHAR_PAIR) {
26+
const pair = CHAR_PAIR[char];
27+
const lastOpenChar = openCharStack.pop();
28+
if (lastOpenChar !== pair) {
29+
return false;
30+
}
31+
}
32+
}
33+
34+
const isEmpty = openCharStack.length === 0;
35+
return isEmpty;
36+
}
37+
// TC: O(n)
38+
// SC: O(n)

0 commit comments

Comments
ย (0)