728x90
문제
풀이1 - 타임 오버
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<String> leftStack = new Stack<>();
Stack<String> rightStack = new Stack<>();
String input = sc.nextLine();
for (char c : input.toCharArray()) {
leftStack .push(String.valueOf(c));
}
int N = sc.nextInt();
sc.nextLine();
for (int i = 0; i < N; i++) {
String command = sc.nextLine();
if (command.isEmpty()) {
continue;
}
char c = command.charAt(0);
switch (c) {
case 'L':
if (!leftStack.isEmpty()) {
rightStack.push(leftStack.pop());
}
break;
case 'D':
if (!rightStack.isEmpty()) {
leftStack.push(rightStack.pop());
}
break;
case 'B':
if (!leftStack.isEmpty()) {
leftStack.pop();
}
break;
case 'P':
if (command.length() >= 3) {
char t = command.charAt(2);
leftStack.push(String.valueOf(t));
}
break;
default:
break;
}
}
while (!leftStack.isEmpty()) {
rightStack.push(leftStack.pop());
}
while (!rightStack.isEmpty()) {
System.out.print(rightStack.pop());
}
sc.close();
}
}
Scanner로 풀고 보니 시간초 제한을 확인 한 후 -> BufferReader로 변경
풀이2
import java.io.*;
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));
Stack<String> leftStack = new Stack<>();
Stack<String> rightStack = new Stack<>();
String[] str =br.readLine().split("");
for(String s : str) {
leftStack.push(s);
}
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++) {
String command = br.readLine();
char c = command.charAt(0);
switch(c) {
case 'L':
if(!leftStack.isEmpty())
rightStack.push(leftStack.pop());
break;
case 'D':
if(!rightStack.isEmpty())
leftStack.push(rightStack.pop());
break;
case 'B':
if(!leftStack.isEmpty()) {
leftStack.pop();
}
break;
case 'P':
char t = command.charAt(2);
leftStack.push(String.valueOf(t));
break;
default:
break;
}
}
while(!leftStack.isEmpty())
rightStack.push(leftStack.pop());
while(!rightStack.isEmpty())
bw.write(rightStack.pop());
bw.flush();
br.close();
bw.close();
}
}
Stack으로 풀었다. 왼쪽과 오른쪽의 스택을 만든 후 풀었다.
728x90
'백준' 카테고리의 다른 글
백준 10866 - Java (0) | 2024.08.24 |
---|---|
백준 1158 - Java (0) | 2024.08.24 |
백준 10845 - java (0) | 2024.08.15 |
백준 1874 - java (0) | 2024.08.13 |
백준 9012 - java (0) | 2024.08.13 |