넘치게 채우기

[LeetCode] 844. Backspace String Compare 본문

PS/LeetCode

[LeetCode] 844. Backspace String Compare

riveroverflow 2023. 10. 19. 21:25
728x90
반응형

https://leetcode.com/problems/backspace-string-compare/description/

 

Backspace String Compare - LeetCode

Can you solve this real interview question? Backspace String Compare - Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. Note that after backspacing an empty text, the tex

leetcode.com

[LeetCode] 844. Backspace String Compare

 

문제 유형 : 스택

문제 난이도 : Easy

 

문제

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

 

두 개의 문자열 s와 t가 주어집니다. 만약 그 두 문자열이 수정되고 나서 같다면, true를 반환하시오. 

'#'는 백스페이스를 의미합니다.

단, 빈 문자열인 상태에서 벡스페이스를 하면, 아무 일도 일어나지 않습니다.

 

풀이

스택에 문자를 하나하나 넣고, #을 찾으면 스택에서 문자를 하나 뺍니다. 빈 스택이면 건너뜁니다.

 

연산을 하고 나서의 두 스택을 비교해주면 됩니다.

 

코드

C++

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
        
        stack<char> sStack;
        stack<char> tStack;

        for(const auto& ch : s) {
            if(ch == '#') {
                if(!sStack.empty()) sStack.pop();
            } else {
                sStack.push(ch);
            }
        }

        for(const auto& ch : t) {
            if(ch == '#') {
                if(!tStack.empty()) tStack.pop();
            } else {
                tStack.push(ch);
            }
        }
        return sStack == tStack;
    }
};
728x90
반응형