반응형

 

시간초과가 발생한 StringBuilder delete, insert를 사용한 오답코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		StringBuilder text = new StringBuilder(br.readLine());

		int M = Integer.parseInt(br.readLine());
		int locateCursor = text.length();
		int textLength = text.length();

		for (int i = 0; i < M; i++) {

			String[] commands = br.readLine().split(" ");

			if (commands[0].equals("L")) {
				if (locateCursor > 0) {
					locateCursor--;
				}
			} else if (commands[0].equals("D")) {
				if (locateCursor < textLength) {
					locateCursor++;
				}
			} else if (commands[0].equals("B")) {
				if (locateCursor > 0) {
					text.deleteCharAt(locateCursor - 1);
					locateCursor--;
					textLength--;
				}
			} else if (commands[0].equals("P")) {
				text.insert(locateCursor, commands[1]);
				locateCursor++;
				textLength++;
			}
		}

		bw.write(text.toString());
		bw.flush();
		bw.close();
	}

}

 

시간초과가 발생하지 않은 Stack 2개를 사용한 정답코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;

public class Main {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		StringBuilder text = new StringBuilder(br.readLine());
		StringBuilder result = new StringBuilder();

		int M = Integer.parseInt(br.readLine());

		Stack<Character> leftWord = new Stack<Character>();
		Stack<Character> rightWord = new Stack<Character>();

		for (int i = 0; i < text.length(); i++) {
			leftWord.push(text.charAt(i));
		}

		for (int i = 0; i < M; i++) {
			String command = br.readLine();

			if (command.equals("L")) {
				if (!leftWord.empty()) {
					rightWord.push(leftWord.pop());
				}
			} else if (command.equals("D")) {
				if (!rightWord.empty()) {
					leftWord.push(rightWord.pop());
				}
			} else if (command.equals("B")) {
				if (!leftWord.empty()) {
					leftWord.pop();
				}
			} else {
				leftWord.push(command.charAt(2));
			}

		}

		while (!leftWord.empty()) {
			rightWord.push(leftWord.pop());
		}

		while (!rightWord.empty()) {
			result.append(rightWord.pop());
		}

		bw.write(result.toString());
		bw.flush();
		bw.close();
	}

}
반응형

'알고리즘 > 백준 문제[추후 옮길예정]' 카테고리의 다른 글

[JAVA] 백준 10799번  (0) 2021.05.08
[JAVA] 백준 17413번  (0) 2021.05.07
[JAVA] 백준 1158번  (0) 2021.05.07
[JAVA] 백준 10845번  (0) 2021.05.07
[JAVA] 백준 9093번  (0) 2021.05.06

+ Recent posts