
์ ๋ฒ ์ฃผ์ ํ์๋ ๋ฌธ์ ์ธ๋ฐ ๋น์์ ๋๊ฒ ํค๋งธ๋ ๊ธฐ์ต์ด ๋๋ค...
๊ฒฐ๊ตญ 40๋ถ ๊ณ ๋ฏผํ๊ณ ํ์ด๋ณด๋ค๊ฐ ํ์ด์ฌ์ผ๋ก ์์ฑ๋ ์ฝ๋๋ฅผ ๋ณด๋ฉด์ ๊ณต๋ถํด์ ๋ค์ ํ์์๋ค
๐๐ผ ์ฐธ๊ณ ์ฝ๋ : https://github.com/neetcode-gh/leetcode/blob/main/python/0020-valid-parentheses.py
class Solution:
def isValid(self, s: str) -> bool:
Map = {")": "(", "]": "[", "}": "{"}
stack = []
for c in s:
if c not in Map:
stack.append(c)
continue
if not stack or stack[-1] != Map[c]:
return False
stack.pop()
return not stack
๐ป ์์ฑ ์ฝ๋
function isValid(s: string): boolean {
// ๋ซ๋ ๊ดํธ ์ง๊ฟ์ ์ ์ฅํ ๊ฐ์ฒด
const parentheses: { [key: string]: string } = { ")": "(", "]": "[", "}": "{" };
// ์ด๋ฆฐ ๊ดํธ๋ฅผ ๋ด์ ์คํ
const stack: string[] = [];
for (const c of s) {
// ์ด๋ฆฐ ๊ดํธ๋ฅผ ๋ฐ๊ฒฌํ์ ๋
if (!(c in parentheses)) {
// ์คํ์ ์ถ๊ฐ
stack.push(c);
continue;
}
// ๋ซ๋ ๊ดํธ๋ฅผ ๋ฐ๊ฒฌํ์ ๋, ์ง๊ฟ์ด ์๊ฑฐ๋ ์ง์ด ๋ง์ง ์์ผ๋ฉด false
if (!stack.length || stack[stack.length - 1] !== parentheses[c]) {
return false;
}
// ์ง๊ฟ์ ์ฐพ์์ผ๋ ์คํ์์ ์ ๊ฑฐ
stack.pop();
}
// ์คํ์ด ๋น์ด์์ผ๋ฉด true, ๊ดํธ๊ฐ ๋จ์์์ผ๋ฉด false
return !stack.length;
}

'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 704. Binary Search (Easy) [TypeScript] (0) | 2024.03.08 |
|---|---|
| 121. Best Time to Buy and Sell Stock (Easy) [TypeScript] (0) | 2024.03.08 |
| 543. Diameter of Binary Tree (Easy) [JavaScript] (1) | 2024.02.13 |
| 104. Maximum Depth of Binary Tree (Easy) [Java] (1) | 2024.02.09 |
| 226. Invert Binary Tree (Easy) [Java] (0) | 2024.02.09 |