C++ Program For Backspace String Comparison

Given two strings s and t, return true if they are equal when both are typed into empty text editors'#' means a backspace character.

Note that after backspacing an empty text, the text will continue empty. 

backspace string compare problem, c++ example, c++ problem, string


Program:

#include <iostream>
#include <string.h>
using namespace std;

bool backspaceCompare(string s, string t)
{
    for(int i = 0; i < s.size(); i++)   //finding backspace character in s string and removing it from string
    {
        if(s[0] == '#')
        {
            s.erase(0,1);
            i--;
        }
        else if(s[i] == '#')
        {
            s.erase(i-1,2);
            i-=2;
        }
    }
    for(int i = 0;i < t.size(); i++)    //finding backspace character in t string and removing it
    {
        if(t[0] == '#')
        {
            t.erase(0,1);
            i--;
        }
        else if(t[i] == '#')
        {
            t.erase(i-1,2);
            i-=2;
        }
    }
    if(s == t)  //checking wheter both strings are equal or not after dealing with backspace characters
        return true;
    
    return false;
}

int main()
{
    string s = "BACKSPY#ACE";
    string t = "#BACT#KSPACE";
    
    if(backspaceCompare(s,t))
        cout << "Both strings are equal.";
    
    else
        cout << "Both strings aren't equal.";

    return 0;
}

Output:

Both strings are equal.
To enhance your coding skill practice more string examples and learn inbuilt functions of string.
C++ Program For Backspace String Comparison C++ Program For Backspace String Comparison Reviewed by Beast Coder on April 28, 2021 Rating: 5

No comments:

Powered by Blogger.