当前位置:网站首页>844. compare strings with backspace

844. compare strings with backspace

2022-06-11 08:56:00 Drag is me

leetcode Force button to brush questions and punch in

subject :844. Compare strings with backspace
describe : Given s and t Two strings , When they are entered into a blank text editor , If the two are equal , return true .# For backspace characters .

Be careful : If you enter backspace characters for empty text , Text continues to be empty .

Their thinking

1、 meet # Just pop up at the top of the stack ;
2、 Originally I wanted to use the stack , As a result, I read the official answer , Oh my god , It turns out that the string itself can be pushed out of the stack , good heavens , Learned .
3、 The string itself is pushed onto the stack push_back(), Out of the stack is pop_back();

Source code ##

class Solution {
    
public:
    string build(string str) {
    
        string ret = "";
        for (int i = 0; i < str.size(); ++i) {
    
            if (str[i] != '#') {
    
                ret.push_back(str[i]);
            } else if (!ret.empty()) {
    
                ret.pop_back();
            }
        }
        return ret;
    }
    bool backspaceCompare(string s, string t) {
    
        return build(s) == build(t); 
    }  
};

原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855010474.html