티스토리 뷰

해당 문제는 파이썬으로 이미 해결한 코드를 c++로 다시 구현하였다.

 

파이썬으로 구현한 코드는 아래에서 확인할 수 있다! ㅎㅎ

https://thisis-undefined.tistory.com/entry/%EB%B0%B1%EC%A4%80-5397-%ED%82%A4%EB%A1%9C%EA%B1%B0-Python

 

[백준] 5397 키로거 Python

백준의 키로거 문제이다. 해당 문제는 스택으로 구현하였다. left 와 right 라는 2 개의 스택을 만든 뒤 '<'일 경우, 왼쪽 원소를 pop하여 right 스택에 넣었고, '>'일 경우, 오른쪽 원소를 pop하여 left 스

thisis-undefined.tistory.com

 

👀 주의해야 할 부분

  • for문에서 i<str1.length()로 바로 사용할 경우, 계속해서 length를 구하기 때문에 변수를 생성하여 넣어준 뒤 사용하는 것이 더 좋다. 가끔 이것만 해결해도 시간초과가 해결될 수 있으니 참고!
  • 다양한 케이스를 생각해야한다. 알고리즘을 풀 때 항상 맞왜틀이 생각난다 😂 이 문제에서는 if와 else if로 조건문을 걸어주었고, 일반 문자가 들어올 경우를 else로 처리해주었는데 알고보니 문자는 '<' 이런 식으로 기호이지만 !stack.empty()에서 맞지 않아 else문으로 바로 빠져버리는 경우때문에 계속 헤맸다! 그러니 조건을 제대로 걸어주었는지, 다양한 케이스들을 생각할 필요가 있다!

 

정답코드

#include<string>
#include<iostream>
#include<stack>
using namespace std;

void init() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
}

int main() {
	init();

	int testcase; cin >> testcase;

	while (testcase--) {
		string str1; cin >> str1;

		stack<char> left, right;
		int str_len = str1.length();
		for (int i = 0; i < str_len; i++) {


			if (str1[i] == '<')
			{
				if (!left.empty())
				{
					right.push(left.top());
					left.pop();
				}
			}
			else if (str1[i] == '>') {
				if (!right.empty()) {
					left.push(right.top());
					right.pop();
				}
			}
			else if (str1[i] == '-') {
				if (!left.empty())
					left.pop();
			}
			else
				left.push(str1[i]);
		}
		string left_string("");
		string right_string = "";
		while (!left.empty())
		{
			left_string += left.top();
			left.pop(); 
		}
		while (!right.empty())
		{
			right_string += right.top();
			right.pop();
		}
		reverse(left_string.begin(), left_string.end());

		cout << left_string + right_string << endl;

	}
	return 0;
}

 

확실히 파이썬보다 c++이 빠르긴 하다...🐤

'알고리즘 문제 풀이 > Algo - c++' 카테고리의 다른 글

[프로그래머스] 베스트앨범 c++  (0) 2021.08.09
(c++) 백준1966 - 프린터 큐  (0) 2020.07.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함