[BOJ] 1406 에디터

알파·2022년 7월 4일
0

스택 두 개를 써서 푸는 문제
이거를 연결리스트라고 하는 건지 뭔지..
L : leftStack에서 pop해서 rightStack에 push
D : rightStack에서 pop해서 leftStack에 push
B : leftStack에서 pop
P $ : leftStack에 $ push

마지막에 leftStack에 있는 거 다 pop해서 rightStack으로 push하고 rightStack을 전부 pop해서 출력해주면 되는 문제

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution1406 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        Stack<Character> leftStack = new Stack<>();
        Stack<Character> rightStack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            leftStack.push(str.charAt(i));
        }

        int n = Integer.parseInt(br.readLine());
        StringTokenizer st;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            String s = st.nextToken();
            if (s.equals("L") && !leftStack.isEmpty()) {
                rightStack.push(leftStack.pop());
            } else if (s.equals("D") && !rightStack.isEmpty()) {
                leftStack.push(rightStack.pop());
            } else if (s.equals("B") && !leftStack.isEmpty()) {
                leftStack.pop();
            } else if (s.equals("P")) {
                leftStack.push(st.nextToken().charAt(0));
            }
        }

        while(!leftStack.isEmpty()) {
            rightStack.push(leftStack.pop());
        }
        StringBuilder sb = new StringBuilder();
        while(!rightStack.isEmpty()) {
            sb.append(rightStack.pop());
        }
        System.out.println(sb);
    }
}
profile
I am what I repeatedly do

0개의 댓글