📌 Stack 활용하기
Stack은 가장 나중에 들어온(push) 데이터가 제일 먼저 나가는(pop) 후입선출(LIFO) 자료구조이다.
import java.util.Stack; Stack<Integer> st = new Stack<Integer>(); // 스택 제일 상단에 데이터 저장 st.push(1); // 스택의 제일 상단(제일 마지막으로 저장된) 요소를 반환 st.peek(); // 스택의 제일 상단에 있는 요소를 반환하고, 해당 요소를 스택에서 제거 st.pop(); // 스택이 비어 있으면 true를, 비어 있지 않으면 false를 반환 st.empty();
toCharArray()
로 문자열을 char 배열로 변환하여 for문 실행import java.util.Stack;
class Solution {
boolean solution(String s) {
Stack<Character> st = new Stack<Character>();
char[] arr = s.toCharArray();
for(char c : arr) {
if(c == '(') {
st.push(c);
} else {
if(!st.empty()) st.pop();
else return false;
}
}
return st.empty();
}
}