[Algorithm/C++] BOJ 9093/ 단어 뒤집기

Sujung Shin·2022년 11월 7일
post-thumbnail

백준 알고리즘 9093번:: 단어 뒤집기 문제

문제 해석

스택 자료구조를 이용하는 전형적인 문제

== 스택의 특징 ==
(1) LIFO(Last-In-First-Out) 구조
(2) 마지막이 나오는 것이 의미가 있을 때
(3) 역순 출력

C++라이브러리에서의 stack

#include <iostream>
#include <string>
#include <stack>

using namespace std;
struct Stack {
	int data[10000];
    int size;
    Stack() {
    	size = 0;
    	}
    void push(int num) {
    		data[size] = num;
            size += 1;
    	}
    bool empty() {
    	if(size == 0) {
        	return true;
        } else {
        	return false;
        	}
    	}
    int pop() {
    	if(empty()) {
        	return -1;
        } else {
        	size -= 1;
            return data[size-1];
        	}
    	}
    int top() {
    	if(empty()) {
        	return -1;
        	} else {
        	return data[size-1];
        	}
   		}
   };
   
   int main() {
   		int n;
    	cin >> n;
    
      Stack s;

      while(n--) {
          string cmd;
          cin >> cmd;
          if (cmd == "push") {
              int num;
              cin >> num;
              s.push(num);
          } else if (cmd == "top") {
              cout << (s.empty()? -1 : s.top()) << '\n';
          } else if (cmd == "size") {
              cout << s.size << '\n';
          } else if (cmd == "empty") {
              cout << s.empty() << '\n';
          } else if (cmd == "pop") {
              cout << (s.empty()? -1 : s.top()) << '\n';
              if (!s.empty()) {
                  s.pop();
                  }
              }
          }
          return 0;
  }
        
       

답안 소스코드:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr); //처리 속도 향상
    int t;
    cin >> t;
    cin.ignore(); 
    /*  
    cin의 입력버퍼에는 테스트 갯수와 개행문자가 있고, 이는 없어지지 않는다. 
    getline()함수에서는 인자입력을 \n(default)으로 구분하기 때문에 
    cin의 입력버퍼를 비워줘야 된다. 
    */
    
    while (test--) {
        string str;
        getline(cin, str); //한줄 씩 읽어와 str에 저장
        str += '\n';
        stack<char> s; //문자열 stack 생성
        for (char ch : str) {
            if (ch == ' ' || ch == '\n') { //만약 공백 혹은 개행문자라면
                while(!s.empty()) { //스택이 빌때까지 쌓인 문자를 빼내어
                    cout << s.top(); //출력
                    s.pop(); 
                }
                cout << ch;
            } else {
                s.push(ch); // 문자를 스택에 밀어넣기
            }
        }
    }
    return 0;
}
profile
백문이불여일타

0개의 댓글