Ticker

6/recent/ticker-posts

Header Ads Widget

Responsive Advertisement

Backspace String Compare

Backspace String Compare


    Backspace String Compare

    Code for comparing two strings after applying backspace by Bob and Alice users. where backspace is '#';
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    bool userLogic(string bob, string alice) {
        // no of elemnts typed by persons
        int sIndex = bob.size();
        int tIndex = alice.size();
        // to track backspace count 
        int sBackspaceCount = 0;
        int tBackspaceCount = 0;
    
        while(sIndex >=0 || tIndex >=0){
            
            while(sIndex >=0){
            if(bob[sIndex]=='#'){
                sBackspaceCount++;
                sIndex--;
            }else if(sBackspaceCount>0){
                sBackspaceCount--;
                sIndex--;
            }else{
                break;
            }
            }
            while(tIndex >=0){
    
            if(alice[tIndex]=='#'){
                tBackspaceCount++;
                tIndex--;
            }else if(tBackspaceCount>0){
                tBackspaceCount--;
                tIndex--;
            }else{
                break;
            }
            }
            if(sIndex >=0 && tIndex >= 0){
                if(bob[sIndex] != alice[tIndex]){
                    return false;
                }
                }else if(sIndex >=0 ||tIndex >=0){
                    return false;
                }
                sIndex--;
                tIndex--;
            
        }
        return true; // or false
    }
    
    int main() {
        string bob, alice;
        getline(cin, bob);
        getline(cin, alice);
        bool result = userLogic(bob, alice);
        cout << (result ? "YES" : "NO") << endl;
        return 0;
    }
     




    Post a Comment

    0 Comments