알고리즘

백준 5397번 키로거 (JAVA)

박카스마시며코딩 2023. 5. 10. 22:06

https://www.acmicpc.net/problem/5397

 

5397번: 키로거

첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스는 한줄로 이루어져 있고, 강산이가 입력한 순서대로 길이가 L인 문자열이 주어진다. (1 ≤ L ≤ 1,000,000) 강산이가 백스페이스를 입

www.acmicpc.net

 

저는 스택 2(stack, temp)개를 이용해여 문제를 해결하였습니다.

< > - 를 제외하고는 stack에 바로 들어가도록 하였습니다.

입력이 < 인 경우

stack에 있는 값 하나를 temp로 옮겼습니다.

입력이 > 인 경우

temp에 있는 값 하나를 stack에 옮겼습니다.

입력이 - 인 경우

stack에서 하나를 뺏습니다.

마지막으로 temp에 있는 모든 값을 stack에 넣어주었고 이 값을 하나씩 빼고 reverse하였습니다.

(stack이기 때문에 역순으로 들어갔기 때문입니다.)

 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.function.Function;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        for(int i = 0 ; i < n ; i++){
            String str = br.readLine();
            System.out.println(cal(str));
        }
    }
    private static final char LEFT = '<';
    private static final char RIGHT = '>';
    private static final char DELETE = '-';
    private static String cal(String str) {
        Stack<Character> stack = new Stack<>();
        Stack<Character> temp = new Stack<>();
        int size = str.length();
        for(int i = 0 ; i < size ; i++){
            char ch = str.charAt(i);
            if(ch == DELETE && !stack.isEmpty()){
                stack.pop();
                continue;
            }
            if(ch == LEFT && !stack.isEmpty()){
                temp.push(stack.pop());
                continue;
            }
            if(ch == RIGHT && !temp.isEmpty()){
                stack.push(temp.pop());
                continue;
            }
            if(ch == DELETE || ch == RIGHT || ch == LEFT){
                continue;
            }
            stack.push(ch);
        }
        while(!temp.isEmpty()){
            stack.push(temp.pop());
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}