728x90
1406 에디터
https://www.acmicpc.net/problem/1406
1406번: 에디터
첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수
www.acmicpc.net


#include <bits/stdc++.h>
using namespace std;
int n,idx;
string m;
string word;
int main()
{
ios::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
cin >> m >> n;
idx = m.length();
for (int i = 0; i < n; ++i)
{
cin >> word;
if ("L" == word)
{
--idx;
if (idx < 0)
idx = 0;
}
else if ("D" == word)
{
++idx;
if (idx > m.length())
idx = m.length();
}
else if ("P" == word)
{
string tmp;
cin >> tmp;
m.insert(idx++, tmp);
}
else if ("B")
{
if (idx <= 0)
continue;
m.erase(idx-1,1);
--idx;
if (idx < 0)
idx = 0;
}
}
cout << m;
}
- 원래 사용한 코드, 시간 초과가 났다.
- string insert부분이나 erase부분에서 느리게 돌아가는듯 하다.
#include <bits/stdc++.h>
using namespace std;
int n;
string m;
string ans;
int main()
{
ios::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
cin >> m >> n;
list<char> li(m.begin(), m.end());
auto cursor = li.end();
for (int i = 0; i < n; ++i)
{
char cmd, c;
cin >> cmd;
if ('L' == cmd)
{
if (cursor != li.begin())
--cursor;
}
else if ('D' == cmd)
{
if (cursor != li.end())
++cursor;
}
else if ('P' == cmd)
{
cin >> c;
li.insert(cursor,c);
}
else if ('B' == cmd)
{
if (cursor != li.begin())
{
--cursor;
cursor = li.erase(cursor);
}
}
}
for (cursor = li.begin(); cursor != li.end(); ++cursor)
cout << *cursor;
}
- list와 iterator를 이용해서 해결했다.
이분의 블로그를 참조해서 해결했다.
https://cocoon1787.tistory.com/718
[C++] 백준 1406번 - 에디터 (스택 풀이 & 연결리스트 풀이)
📖 문제 📋 Stack 풀이 코드 #include #include #include using namespace std; int main() { int M; string s = ""; stack left; stack right; cin >> s; for (int i = 0; i < (int)s.size(); i++) { left.push(s[i]); } cin >> M; for (int i = 0; i < M; i++) {
cocoon1787.tistory.com
728x90
'Study > Baekjoon' 카테고리의 다른 글
[백준/C++] 4375 1 (0) | 2024.04.27 |
---|---|
[백준/C++] 1107 리모컨 (0) | 2024.04.21 |
[백준/C++] 11728 배열 합치기 (0) | 2024.04.08 |
[백준/C++] 1269 대칭 차집합 (1) | 2024.04.06 |
[백준/C++] 14502 연구소 (0) | 2024.04.01 |