【LeetCode】844. 比较含退格的字符串

给定 ST 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。

解题思路:用栈保存字符串中的字符,当遇到#时,pop元素出栈。

bool Solution::backspaceCompare(string S, string T)
{
    unsigned int index = 0;
    stack<int> stacks,stackt;
    
    while(S[index] != '\0')
    {
        if(S[index] != '#')
        {
            stacks.push(S[index]);
        }
        else
        {
            if(stacks.empty() != true)
            {
                stacks.pop();
            }
        }
        index ++;
    }
    index = 0;
    while(T[index] != '\0')
    {
        if(T[index] != '#')
        {
            stackt.push(T[index]);
        }
        else
        {
            if(stackt.empty() != true)
            {
                stackt.pop();
            }
        }
        index ++;
    }
    if(stackt.size() != stacks.size())
    {
        return false;
    }
    else
    {
        while((stackt.empty() != true) && (stacks.empty() != true))
        {
            if(stackt.top() != stacks.top())
            {
                return false;
            }
            else
            {
                stackt.pop();
                stacks.pop();
            }
        }
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/syc233588377/article/details/86130643