• 문제 링크
1406번: 에디터
첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수
www.acmicpc.net
• 풀이 과정
두 개의 Stack 을 생성, 각각 stk, tmp 로 명칭하고 이를 활용해 커서의 움직임에 따른 문자열의 변화를 구현한다.
기본적으로 stk 이 커서의 왼쪽 영역, tmp가 커서의 오른쪽 영역이라고 인식하며 풀이한다.
각각의 명령어를 스택의 LIFO 구조를 활용하여 L, D, B 는 값이 비어있지 않은 경우 값을 이동 및 삭제,
P $ 의 경우 할당된 값을 stk에 삽입한다.
두번째 입력을 예시로 들어 각각 스택의 값 변화를 나타내면 아래와 같다.
cursor | L | L | L | L (pass) | L (pass) | P x | L | B (pass) | P y |
stk(abc) | ab | a | empty | empty | empty | x | empty | emtpy | y |
tmp | c | cb | cba | cba | cba | cba | cbax | cbax | cbax |
최종적으로 tmp 변수의 값을 tmp 가 비어질 때까지 모두 pop() 하여 stk 변수에 삽입 후 문자열로 변환시켜 출력한다.
• 풀이 코드
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 NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
Stack<Character> stk = new Stack<>();
Stack<Character> tmp = new Stack<>();
String n = br.readLine();
for (int i = 0; i < n.length(); i++)
stk.push(n.charAt(i));
int m = Integer.parseInt(br.readLine());
for (int i = 0; i < m; i++) {
String[] input = br.readLine().split(" ");
if (!stk.empty() && input[0].equals("L"))
tmp.push(stk.pop());
if (!tmp.empty() && input[0].equals("D"))
stk.push(tmp.pop());
if (!stk.empty() && input[0].equals("B"))
stk.pop();
if (input[0].equals("P"))
stk.push(input[1].charAt(0));
}
while (!tmp.empty())
stk.push(tmp.pop());
StringBuilder sb = new StringBuilder();
for (Character c : stk)
sb.append(c);
bw.write(sb + "\n");
bw.flush();
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 9093 단어 뒤집기 - Data Structure / Java (0) | 2022.06.18 |
---|---|
[백준] 10799 쇠막대기 - Data Structure / Java (0) | 2022.06.17 |
[백준] 1874 스택 수열 - Data Structure / Java (0) | 2022.06.15 |
[백준] 1158 요세푸스 문제 - Data Structure / Java (0) | 2022.06.14 |
[백준] 9012 괄호 - Data Structure / Java (0) | 2022.06.13 |
댓글