GitHubSeob

C++ / 백준 / 1406 / 에디터 본문

Baekjoon/Silver

C++ / 백준 / 1406 / 에디터

GitHubSeob 2021. 10. 26.

문제

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

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

문제풀이

처음에 string insert, erase를 써서 풀었는데 시간 초과가 나서 질문글을 보다가 stack으로 푼 사람이 있어서 stack으로 풀었다.

stack을 두 개를 선언하여 앞, 뒤 스택을 만들었다.

명령어는 L, D, B, P로 총 네 가지가 있다.

L일 때는 왼쪽으로 한 칸 이동이므로 앞 스택의 top값을 뒷 스택에 push 하고 앞 스택을 pop 한다.

그러면 앞 스택의 top을 뒷 스택의 top으로 옮긴 셈이다.

D일 때는 반대로 뒷 스택의 top값을 앞 스택의 top으로 옮긴다.

B일 때는 앞 스택의 top을 없애기 위해 pop을 한다.
P일 때는 앞 스택에 push 한다.

모든 명령어가 종료되어 출력할 때는 앞 스택을 모두 뒷 스택으로 옮기고 뒷 스택의 top을 순서대로 출력한다.

 

코드

#include <iostream>
#include <stack>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	stack<char>front;
	stack<char>back;
	string s1("");
	cin >> s1;
	char cmd(' '), cmd2(' ');

	int idx(0);
	int cnt(0);

	for (idx = 0; idx < s1.size(); ++idx)
		front.push(s1[idx]);
	cin >> cnt;

	for (idx = 0; idx < cnt; ++idx) {
		cin >> cmd;

		if (cmd == 'L') {
			if (!front.empty()) {
				back.push(front.top());
				front.pop();
			}
		}

		else if (cmd == 'D') {
			if (!back.empty()) {
				front.push(back.top());
				back.pop();
			}

		}
		else if (cmd == 'B') {
			if (!front.empty())
				front.pop();
		}
		else if (cmd == 'P') {
			cin >> cmd2;
			front.push(cmd2);
		}
	}
	while (!front.empty()) {
		back.push(front.top());
		front.pop();
	}
	
	while (!back.empty()) {
		cout << back.top();
		back.pop();
	}
}