๐Ÿฅž BE
home

20_Valid Parentheses

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/07/10
ํƒœ๊ทธ
์ž๋ฃŒ๊ตฌ์กฐ
๋‚œ์ด๋„
Easy
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

import java.util.ArrayDeque; import java.util.Deque; class Solution { public boolean isValid(String s) { Deque<Character> stack = new ArrayDeque<>(); for (char ch : s.toCharArray()) { // ์—ด๋ฆผ ๊ด„ํ˜ธ๋Š” push if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } else { // 1. ์Šคํƒ์ด ๋น„์–ด์žˆ์„ ๊ฒฝ์šฐ, 2. ์—ด๋ฆผ๊ณผ ๋‹ซํž˜ ๊ด„ํ˜ธ๊ฐ€ ๋‹ค๋ฅผ ๊ฒฝ์šฐ if (stack.isEmpty()) { return false; } char top = stack.pop(); if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) { return false; } } } // ์Šคํƒ ๋น„์–ด์žˆ์œผ๋ฉด ๋ชจ๋‘ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ง์ง€์–ด์ง„ ๊ฒƒ -> true return stack.isEmpty(); } }
Java
๋ณต์‚ฌ

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

์—ด๋ฆผ ๊ด„ํ˜ธ์™€ ๋‹ซํž˜ ๊ด„ํ˜ธ๋ฅผ ๋น„๊ตํ•˜๋Š” ๋กœ์ง์„ ์ž˜ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.