문제 풀이/백준

[백준]1406번. 에디터(JAVA)

27200 2024. 4. 5. 21:43

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


풀이

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        String s = br.readLine();
        StringBuilder stringBuilder = new StringBuilder(s);
        int n = Integer.parseInt(br.readLine());
        int index = s.length();

        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            String command = st.nextToken();
            switch (command) {
                case "P":
                    char c = st.nextToken().charAt(0);
                    if (index <= stringBuilder.length()) {
                        stringBuilder.insert(index, c);
                        index++;
                    }
                    break;
                case "L":
                    if (index > 0) {
                        index--;
                    }
                    break;
                case "D":
                    if (index < stringBuilder.length()) {
                        index++;
                    }
                    break;
                case "B":
                    if (index > 0) {
                        stringBuilder.deleteCharAt(index - 1);
                        index--;
                    }
                    break;
            }
        }


        System.out.println(stringBuilder.toString());
    }
}

 

stringBuilder 을 이용해서 조건에 맞게 문자열을 조작하는 문제이다. 문법만 알고있다면 어렵지 않게 해결하겠다 싶었는데 중간에 조건 검사문에서 if, else-if 문을 사용했더니 시간초과가 나왔다. 아마 쓸데없는 조건검사를 너무 여러번 하는 탓인것 같다. 따라서 조건 검사를 한번만 진행해도 되는 스위치문을 사용했다. 상황에따라 잘 사용해야 할 것 같다..