본문 바로가기

알고리즘 공부/백준

1406 에디터 by C++

문제

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

 

해결한 방법

저번에 string만으로 문제를 해결할때 시간이 단축되서 string으로 해결하려고 코드를 짜봤는데 아무리해도 시간 제한을 통과할 수 없었습니다. 알고리즘 분류에 stack이 있어서 stack으로 시도해봤더니 통과했네요

#include <iostream> // cin, cout, getline
#include <string> // string
#include <stack> // stack
using namespace std;

int main()
{
	stack<char> s1, s2;
	string str;
	cin >> str;
	cin.ignore();
	int i;
	for (i = 0; i < str.size(); i++)
	{
		s1.push(str[i]);
	}
	
	int line_num;
	cin >> line_num;
	cin.ignore();
	string command;
	while (line_num--) {
		getline(cin, command);
		if (command[0] == 'L') {
			if (!s1.empty()) {
				s2.push(s1.top());
				s1.pop();
			}
		}
		else if (command[0] == 'D') {
			if (!s2.empty()) {
				s1.push(s2.top());
				s2.pop();
			}
		}
		else if (command[0] == 'B') {
			if (!s1.empty()) {
				s1.pop();
			}
		}
		else {
			s1.push(command[2]);
		}
	}

	// 출력을 위한 정리
	int s1_size = s1.size();
	while(s1_size--) {
		s2.push(s1.top());
		s1.pop();
	}

	// 출력
	int s2_size = s2.size();
	while(s2_size--){
		printf("%c", s2.top());
		s2.pop();
	}

	return 0;
}

개선한 방법

개선할만 여지가 없는 것은 아니나 방법이 크게 다르지 않아 코드를 개선할만한 방법을 찾지 못했습니다.

처음으로 다른 모범답안들이랑 비슷하게 작성해서 기분이 좋으면서도 새로운 방법을 배우지 못해 아쉽습니다.

'알고리즘 공부 > 백준' 카테고리의 다른 글

1158 요세푸스 with C++  (0) 2022.07.05
10845 큐 with C++  (0) 2022.07.04
1874 스택 수열 by C++  (0) 2022.07.03
9012 괄호 by C++  (0) 2022.07.02
9093 단어 뒤집기 by C++  (0) 2022.07.02