알고리즘

[C++] 백준 5397번 키로거

J3SUNG 2019. 9. 26. 18:58
728x90

스택을 2개 이용해서 문제를 풀었습니다.

기본적으로 A라는 스택에 문자를 넣고
커서가 앞으로 이동되면 B라는 스택에 커서 이후의 문자들을 넣어줍니다.
커서가 다시 뒤로 이동되면 B의 커서를 A의 커서에 담는 식으로 하였습니다.

 

#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
	int ts;
	string str;
	stack<char> a;
	stack<char> b;
	vector<char> result;

	cin >> ts;

	while(ts--) {
		result.clear();

		cin >> str;

		for (int i = 0; i < str.length(); ++i) {
			if (str[i] == '-') {
				if (!a.empty()) {
					a.pop();
				}
			}
			else if (str[i] == '<') {
				if (!a.empty()) {
					b.push(a.top());
					a.pop();
				}
			}
			else if (str[i] == '>') {
				if (!b.empty()) {
					a.push(b.top());
					b.pop();
				}
			}
			else {
				a.push(str[i]);
			}
		}

		while (!b.empty()) {
			a.push(b.top());
			b.pop();
		}
		while (!a.empty()) {
			result.push_back(a.top());
			a.pop();
		}
		reverse(result.begin(), result.end());
		
		for (int i = 0; i < result.size(); ++i) {
			cout << result[i];
		}
		cout << endl;
	}

	return 0;
}