본문 바로가기
알고리즘/백준

[백준 1406] 에디터 (cpp, stack)

by RoJae 2021. 12. 19.

🚀  들어가며...

  • 스택을 사용해서 풀 수 있는 문제이다.
  • 커서를 기준으로, 앞과 뒤로 스택을 두개를 준다.
  • 스택1 : 커서 앞
  • 스택2 : 커서 뒤
  • 명령어에 맞추어서 스택에 할당한다.
  • 마지막으로는 스택2에 모두 담아서, 출력시켜준다.

 

🔗  문제

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

 

1406번: 에디터

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

www.acmicpc.net

 

 

💌 소스코드

#include<iostream>
#include<stack>
#include<string>

using namespace std;

int main(){
	string str;
	stack<char> st1;
	stack<char> st2;
	int t;
	
	cin >> str;
	int n = str.size();
	for(int i = 0; i < n; i++)
		st1.push(str.at(i));

	cin >> t;

	for(int i =0; i < t; i++)
	{
		char command;
		cin >> command;
		
		if(command == 'L'){
			if(st1.size() != 0){
				st2.push(st1.top());
				st1.pop();
			}
		}
		else if(command == 'P'){
			char alpha;
			cin >> alpha;
			st1.push(alpha);;
		}
		else if(command == 'D'){
			if(st2.size() != 0){
				st1.push(st2.top());
				st2.pop();
			}	
		}
		else{	// command = B
			if(!st1.empty())
				st1.pop();
		}
	}
	while(!st1.empty()){
		st2.push(st1.top());
		st1.pop();
	}	
	while(!st2.empty()){
		cout<<st2.top();
		st2.pop();
	}
}

 

 

 

댓글