1406번: 에디터
첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수
www.acmicpc.net
이 문제는 스택을 2개 사용해서 해결할 수 있다.
예제 입력이 다음과 같을 때 문제 해결 과정을 그림으로 알아보자.
예제 입력
calt
9
L
L
P s
P t
D
D
B
P e
L
예제 출력
castle
커서의 위치를 잘 확인해보자.
커서는 항상 스택 s의 최상단을 가리킨다.
문제에서는 P 연산 시 커서 왼쪽에 문자를 추가한다고 했지만 그냥 스택 s에 문자를 삽입하면 된다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define endl '\n'
string str;
int N;
vector<char> s, temp;
void initInput() {
cin >> str >> N;
for (int i = 0; i < str.length(); i++)
s.push_back(str[i]);
}
void solve() {
while (N--) {
char cmd; cin >> cmd;
if (cmd == 'L') {
if (s.empty()) continue;
temp.push_back(s.back());
s.pop_back();
}
else if (cmd == 'D') {
if (temp.empty()) continue;
s.push_back(temp.back());
temp.pop_back();
}
else if (cmd == 'B') {
if (s.empty()) continue;
s.pop_back();
}
else {
char input; cin >> input;
s.push_back(input);
}
}
while (!temp.empty()) {
s.push_back(temp.back());
temp.pop_back();
}
for (int i = 0; i < s.size(); i++)
cout << s[i];
}
int main(void) {
cout.tie(NULL); cin.tie(NULL); ios_base::sync_with_stdio(false);
initInput();
solve();
return 0;
}
'Baekjoon' 카테고리의 다른 글
[C/C++] 백준 11057번 - 오르막 수 (0) | 2023.08.04 |
---|---|
[C/C++] 백준 1475번 - 방 번호 (0) | 2023.08.04 |
[C/C++] 백준 10799번 - 쇠막대기 (0) | 2023.08.01 |
[C/C++] 백준 1992번 - 쿼드트리 (0) | 2023.08.01 |
[C/C++] 백준 11497번 - 통나무 건너뛰기 (0) | 2023.05.31 |