코딩테스트(알고리즘)/baekjoon
[baekjoon] 키로거 5397 (Javascript,c++)
Cafe Mocha
2022. 6. 14. 20:13
5397번: 키로거
첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스는 한줄로 이루어져 있고, 강산이가 입력한 순서대로 길이가 L인 문자열이 주어진다. (1 ≤ L ≤ 1,000,000) 강산이가 백스페이스를 입
www.acmicpc.net
접근 방법
알고리즘 : 연결 리스트
1. c++은 STL리스트를 활용해 풀이
2. Javascript로는 시간초과 발생
자료구조 문제를 풀며 C++의 필요성을 많이 느끼고 있다.
Javascript
const [T, ...input] = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const resultLog = [];
for (let i = 0; i < T; i++) {
const testStr = input[i].split('');
let left = [];
let right = [];
for (let j = 0; j < testStr.length; j++) {
if (testStr[j] === '<') {
if (left.length > 0) {
right.push(left.pop())
}
} else if (testStr[j] === '>') {
if (right.length > 0) {
left.push(right.pop())
}
} else if (testStr[j] === '-') {
if (left.length > 0) {
left.pop();
}
} else {
left.push(testStr[j]);
}
}
left = left.concat(right.reverse());
resultLog.push(left.join(''))
}
console.log(resultLog.join('\n'));
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin); //제출 시 삭제
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
for (int i = 0; i < t; i++) {
list<char> L = {};
string s;
auto p = L.begin();
cin >> s;
for (auto c : s) {
if (c == '<') {
if (p != L.begin()) p--;
}
else if (c == '>') {
if (p != L.end()) p++;
}
else if (c == '-') {
if (p != L.begin()) {
p--;
p = L.erase(p);
}
}
else
L.insert(p, c);
}
for (auto c : L) cout << c;
cout << '\n';
}
}