알고리즘
스택
체감 난이도
★ ★ ☆ ☆ ☆
다시 풀 수 있는가?
YES
1. isEmpty()
해설을 봤는데, 안봤으면 푸는데 굉장히 오래 걸렸을 것 같다.
isEmpty() 했을 때 비어있지 않으면 닫히지 않은 괄호라는 것을 의미한다.
if (c == '(') {
stack.push(c);
}
else if (c == ')') {
if (stack.isEmpty()) {
ans++;
}
else {
stack.pop();
}
}
전체 코드 ▼
더보기
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class BOJ11899 {
public int solution() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
Stack<Character> stack = new Stack<>();
int ans = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(') {
stack.push(c);
}
else if (c == ')') {
if (stack.isEmpty()) {
ans++;
}
else {
stack.pop();
}
}
}
ans += stack.size();
return ans;
}
public static void main(String[] args) throws Exception {
int ans = new BOJ11899().solution();
System.out.println(ans);
}
}