본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1047. Remove All Adjacent Duplicates In String

반응형

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/description/

 

Remove All Adjacent Duplicates In String - LeetCode

Can you solve this real interview question? Remove All Adjacent Duplicates In String - You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedl

leetcode.com

자료구조 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 ans와 stack st를 선언해줍니다.

📔 풀이과정

1. s의 원소에 대해 for loop를 수행하며 다음을 수행합니다.

1-1. 현재 문자 c와 stack의 top이 같다면 stack에서 해당 원소를 pop해줍니다.

1-2. stack에 문자 c를 push해줍니다.

 

2. stack의 모든 원소를 pop하면서 ans에 문자를 붙여줍니다.

3. 뒤집어진 형태이므로 ans를 reverse해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    string removeDuplicates(string s) {
        string ans;
        stack <char> st;
        for(auto c : s) {
            if(st.size() && st.top() == c) {
                while(st.size() && st.top() == c) {
                    st.pop();
                }
                continue;
            }
            st.push(c);
        }
        while(st.size()) {
            ans += st.top();
            st.pop();
        }
        reverse(ans.begin(), ans.end());
        return ans;

    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.