문제 링크입니다: https://programmers.co.kr/learn/courses/30/lessons/12973
코딩테스트 연습 - 짝지어 제거하기
짝지어 제거하기는, 알파벳 소문자로 이루어진 문자열을 가지고 시작합니다. 먼저 문자열에서 같은 알파벳이 2개 붙어 있는 짝을 찾습니다. 그다음, 그 둘을 제거한 뒤, 앞뒤로 문자열을 이어 붙
programmers.co.kr
스택을 이용하는 문제였습니다.
알고리즘은 아래와 같습니다.
1. 스택에 문자열의 첫 번째 알파벳을 push 해줍니다.
2. 두 번째 알파벳부터 마지막 알파벳까지 스택의 top()과 비교해서 같을 경우 짝을 이루므로 pop()을 해주고 짝이 아니라면 push를 해줍니다.
3. 2번 과정을 거치고 나서 스택이 비어있다면 짝지어 제거하기가 성공한 것이고 크기가 1 이상이라면 실패한 것입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <stack> | |
using namespace std; | |
int solution(string s) | |
{ | |
stack<char> st; | |
st.push(s[0]); | |
for (int i = 1; i < s.length(); i++) | |
{ | |
if (!st.empty() && st.top() == s[i]) | |
{ | |
st.pop(); | |
continue; | |
} | |
st.push(s[i]); | |
} | |
return st.empty(); | |
} | |
int main(void) | |
{ | |
string s = "baaabbaaab"; | |
cout << solution(s) << "\n"; | |
return 0; | |
} |

개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] 단어 퍼즐 (0) | 2021.09.30 |
---|---|
[Programmers] 예상 대진표 (0) | 2021.09.30 |
[Programmers] 모두 0으로 만들기 (0) | 2021.09.29 |
[Programmers 위클리 챌린지 8주차] 최소직사각형 (0) | 2021.09.27 |
[Programmers] 로또의 최고 순위와 최저 순위 (0) | 2021.09.27 |