반응형

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

 

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

 

각 문자열에 대해 투포인터를 이용하여 backspace가 적용되었을 때의 문자열과 길이를 구해줍니다.

O(1)의 공간과 O(n)의 시간으로 풀 수 있었습니다.

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        int sSize = removeBackspaceAndGetSize(s);
        int tSize = removeBackspaceAndGetSize(t);
            
        if (sSize != tSize) return false;
        for(int i=0; i<sSize; i++)
            if(s[i] != t[i]) return false;
        return true;
    }

private:
    int removeBackspaceAndGetSize(string& str) {
        int sz = 0;
        for(char c : str)
            if(c == '#') sz -= sz > 0;
            else str[sz++] = c;
        return sz;
    }
};
반응형

'Algorithm' 카테고리의 다른 글

LeetCode 342. Power of Four  (1) 2023.10.23
LeetCode 341. Flatten Nested List Iterator  (0) 2023.10.20
LeetCode 2050. Parallel Courses III  (0) 2023.10.18
LeetCode 1361. Validate Binary Tree Nodes  (0) 2023.10.18
LeetCode 119. Pascal's Triangle II  (0) 2023.10.16

+ Recent posts