Leetcode每日一题:844.backspace-string-compare(比较含退格的字符串)

在这里插入图片描述
思路:用栈的机制模拟退格过程;本来不想用这种方法的,对时间复杂度不满意,想用双指针写但没写出来;
在这里插入图片描述

string compare(string s)
{
    
    
    string res = "";
    int len = s.size();
    int num = 0; //最好手动用num记录数组元素个数,如果每次都用s.size()会导致时间复杂度增大
    for (int i = 0; i < len; i++)
    {
    
    
        if (s[i] != '#')
        {
    
    
            res.push_back(s[i]);
            num++;
        }
        else
        {
    
    
            if (num < 0) 
            {
    
    
                continue;
            }
            else //如果还有元素,就pop出
            {
    
    
                res.pop_back();
                num--;
            }
        }
    }
    cout << res<<endl;
    return res;
}

bool backspaceCompare(string S, string T)
{
    
    
    return compare(S) == compare(T);
}

猜你喜欢

转载自blog.csdn.net/wyll19980812/article/details/109158557