llllmz

导航

844. 比较含退格的字符串c

bool backspaceCompare(char* s, char* t) {
    int ns=strlen(s),nt=strlen(t);
    int head=0,tail=0;
    int n1=0,n2=0;
    while(tail<ns){
        if(head==0&&s[tail]=='#'){
            tail++;
        }else if(s[tail]=='#'){
            tail++;
            head--;
            n1--;
        }else{
            n1++;
            s[head]=s[tail];
            head++;
            tail++;
        }
    }
    head=0,tail=0;
    while(tail<nt){
        if(head==0&&t[tail]=='#'){
            tail++;
        }else if(t[tail]=='#'){
            tail++;
            head--;
            n2--;
        }else{
            n2++;
            t[head]=t[tail];
            head++;
            tail++;
        }
    }
    printf("%d %d",n1,n2);
    if(n1!=n2) return false;
    for(int i=0;i<n1;i++){
        if(s[i]!=t[i]) return false;
    }
    return true;
}

结果:

posted on 2024-03-12 22:52  神奇的萝卜丝  阅读(17)  评论(0)    收藏  举报