Stack_괄호 문제
✅ 올바른 괄호인지 판별하여 맞으면 “YES”, 아니면 “NO”를 출력하세요.
(())() “YES”
(()())) “NO”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.*;
class Main {
public String solution(String input){
String answer= "NO";
Stack<Character> stack= new Stack<>();
for(char c: input.toCharArray()){
if(c == '(') stack.push(c);
else if(c == ')'){
if(stack.isEmpty()) return answer;
else stack.pop();
}
}
if(stack.isEmpty()) answer= "YES";
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
String input= sc.next();
System.out.print(T.solution(input));
}
}
//⭐️input:
//(()(()))(()
//⭐️output:
//NO
🔵 ThingsILearned
✔️ ()
, {}
등 괄호가 나오는 문제는 stack으로 풀어야 할 확률이 높다.
stack: 구덩이에 뭔가를 집어넣고 뺴는 구조
따라서 LIFO(last in, first out)
method로는 push
, pop
, isEmpty
등이 있다.
This post is licensed under CC BY 4.0 by the author.