844. Backspace String Compare(双指针法)

844. Backspace String Compare

代码如下

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        int first=s.length()-1,second=t.length()-1;
        int space_s=0,space_t=0;
        while(first>=0 || second>=0){
            while(first>=0){
                if(s[first]=='#'){
                    first--;
                    space_s++;
                }else if(space_s){
                    first--;
                    space_s--;
                }else if(!space_s){
                    break;
                }
            }
            while(second>=0){
                if(t[second]=='#'){
                    second--;
                    space_t++;
                }else if(space_t){
                    space_t--;
                    second--;
                }else if(!space_t){
                    break;
                }
            }
            if(first>=0 && second>=0){
                if(s[first]!=t[second])
                    return false;
            }else{
                if(first>=0|| second>=0)
                    return false;
            }
            first--,second--;
        }
        return true;
    }
};

大致的想法,大循环用于比较小循环找到的字符是否相等,同时,考虑到两个字符串不一定相等,所以是大循环是或的条件,但在比较字符时if是且的条件,这里不要在外面判断,要在大循环里就把长度不同的给排掉,因为出了循环不好判断,还有个原因左边化完全变空字符串,此时也是满足条件

还有一种是栈的做法

class Solution {
public:
    bool backspaceCompare(string s, string t) {
        stack<char> a,b;
        int sizes=s.length(),sizet=t.length();
        for(int cnt=0;cnt<sizes;cnt++){
            if(s[cnt]=='#' && !a.empty()){
                a.pop();
                continue;
            }else if(s[cnt]=='#'){
                continue;
            }
            a.push(s[cnt]);
        }
        for(int cnt=0;cnt<sizet;cnt++){
            if(t[cnt]=='#' && !b.empty()){
                b.pop();
                continue;
            }else if(t[cnt]=='#'){
                continue;
            }
            b.push(t[cnt]);
        }
        if(b.size()==a.size()){
            while(!a.empty()){
                if(b.top()==a.top()){
                    b.pop(),a.pop();
                    continue;
                }else
                    return false;
            }
        }else
            return false;
        return true;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cjz-lxg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值