Post List

[BOJ] 백준 5397 키로거

[BOJ] 백준 5397 키로거



문제 링크 : https://www.acmicpc.net/problem/5397


이 문제는  문자열을 입력 받았을 때 '<', '>', '-' 을 제외한 문자들만 출력을 하는 문제이다.
스택을 이용하면 쉽게 풀린다. '<' 나 '>' 문자를 입력받은 경우 원본 스택의 Top을 임시스택으로 Push / 임시스택의 Top을 원본스택으로 Push 하면 되고, '-' 인 경우 원본스택을 하나 Pop 하면 된다.


소스코드 :




#include 
#include 
#include 
using namespace std;

int main() {
 int t;
 cin >> t; cin.ignore();
 
 while (t--) {
  string s;
  cin >> s; cin.ignore();
  stack st;
  stack tmp;
  for (int i = 0; i < s.length(); i++) {

   // ' - ' 을 입력받은 경우 원본스택 pop;
   if (s[i] == '-') {
    if (!st.empty()) st.pop();
   }

   // '<' 을 입력받은 경우 임시스택에 원본 top을 push
   else if (s[i] == '<') {
    if (!st.empty()) {
     tmp.push(st.top());
     st.pop();
    }
   }

   // '>' 을 입력받은 경우 원본스택에 임시 top을 push
   else if (s[i] == '>') {
    if (!tmp.empty()) {
     st.push(tmp.top());
     tmp.pop();
    }
   }

   // 그 외의 문자일 경우 원본스택에 push
   else {
    st.push(s[i]);
   }
  }

  // 임시스택에 잔여 문자들이 있을경우 원본스택으로 옮김.
  if (!tmp.empty()) {
   int tsize = tmp.size();
   while (tsize--) {
    st.push(tmp.top());
    tmp.pop();
   }
  }

  // 출력 로직
  int ssize = st.size();
  for (int i = 0; i < ssize; i++) {
   tmp.push(st.top());
   st.pop();
  }
  for (int i = 0; i < ssize; i++) {
   cout << tmp.top();
   tmp.pop();
  }
  cout << '\n';
 }
}

댓글