์ฝ๋
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
๋ณต์ฌ
๋ฌธ์ ํด๊ฒฐ ์์ด๋์ด
์ด๋ฆผ ๊ดํธ์ ๋ซํ ๊ดํธ๋ฅผ ๋น๊ตํ๋ ๋ก์ง์ ์ ๋ง๋ค์ด์ผ ํ๋ค.