끄적끄적 코딩
article thumbnail
Published 2019. 9. 26. 18:58
[C++] 백준 5397번 키로거 알고리즘

스택을 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;
}

'알고리즘' 카테고리의 다른 글

[C++] 백준 5598번 카이사르 암호  (0) 2019.09.27
[C++] 백준 2799번 블라인드  (0) 2019.09.26
[C++] 백준 1773번 폭죽쇼  (0) 2019.09.26
[C++] 백준 5567번 결혼식  (0) 2019.09.26
[C++] 백준 1068번 트리  (0) 2019.09.26

검색 태그