알고리즘/프로그래머스

표편집 (자바)

김어찐 2021. 9. 12. 13:50
728x90
package prog;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Stack;

public class 표편집 {
    public static void main(String[] args) {
        Solution_표편집 s= new Solution_표편집();
        System.out.println(s.solution(8,	2,new String[] {"D 2","C","U 3","C","D 4","C","U 2","Z","Z"}));
        System.out.println(s.solution(8,	2,new String[] {"D 2","C","U 3","C","D 4","C","U 2","Z","Z","U 1","C"}));
    }
}

class Solution_표편집{
    public String solution(int n, int k, String[] cmd) {

        int tableSize=n;
        Stack<Integer> stack = new Stack<>();

        for (String oper : cmd) {
            String[] operList = oper.split(" ");

            if(operList[0].equals("U")){
                k-=Integer.parseInt(operList[1]);
            }
            else if(operList[0].equals("D")){
                k+=Integer.parseInt(operList[1]);
            }
            else if(operList[0].equals("C")){
                stack.add(k);
                tableSize--;
                if (k ==tableSize ) {
                    k--;
                }
            }
            else{
                int pos = stack.pop();
                if(pos<=k)k++;
                tableSize++;
            }


        }
        StringBuilder answer= new StringBuilder();
        for (int i = 0; i < tableSize; i++) {
            answer.append('O');
        }
        while (!stack.isEmpty()) {
            int pos = stack.pop();
            answer.insert(pos, 'X');
        }
        return answer.toString();
    }
}
728x90