Check if two strings after processing backspace character are equal or not
Last Updated :
12 Apr, 2023
Given two strings s1 and s2, let us assume that while typing the strings there were some backspaces encountered which are represented by #. The task is to determine whether the resultant strings after processing the backspace character would be equal or not.
Examples:
Input: s1= geee#e#ks, s2 = gee##eeks
Output: True
Explanation: Both the strings after processing the backspace character becomes “geeeeks”. Hence, true.
Input: s1 = equ#ual, s2 = ee#quaal#
Output: False
Explanation: String 1 = equ#ual, after processing the backspace character becomes “equal” whereas string 2 = equ#ual, after processing the backspace character becomes “equaa”. Hence, false.
Approach:
To solve the problem mentioned above we have to observe that if the first character is ‘#’, that is there is certainly no character typed initially and hence we perform no operation. When we encounter any character other than ‘#’, then we add the character just after the current index. When we encounter a ‘#’, we move one index back, so instead of deleting the character, we just ignore it. Then finally compare the two strings by comparing each character from start to end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string removeBackspaces(string& s)
{
int n = s.size();
int idx = 0;
for ( int i = 0; i < n; i++) {
if (s[i] != '#' ) {
s[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
if (idx < 0)
idx = 0;
}
return s.substr(0, idx);
}
int main()
{
string s = "equ#ual" ;
string t = "gee##eeks" ;
if (removeBackspaces(s) == removeBackspaces(t))
cout << "True" ;
else
cout << "False" ;
return 0;
}
|
Java
import java.io.*;
public class Main {
public static String removeBackspaces(String s) {
int n = s.length();
int idx = 0 ;
for ( int i = 0 ; i < n; i++) {
if (s.charAt(i) != '#' ) {
s = s.substring( 0 , idx) + s.charAt(i) + s.substring(idx + 1 );
idx++;
}
else if (s.charAt(i) == '#' && idx >= 0 ) {
idx--;
}
if (idx < 0 )
idx = 0 ;
}
return s.substring( 0 , idx);
}
public static void main(String[] args) {
String s = "equ#ual" ;
String t = "gee##eeks" ;
if (removeBackspaces(s).equals(removeBackspaces(t)))
System.out.println( "True" );
else
System.out.println( "False" );
}
}
|
Python3
def removeBackspace(s) - > str :
n = len (s)
idx = 0
for i in range ( 0 , n):
if (s[i] ! = '#' ):
s = s[:idx] + s[i] + s[idx + 1 :]
idx + = 1
elif (s[i] = = '#' and idx > = 0 ):
idx - = 1
if (idx < 0 ):
idx = 0
ans = ""
for i in range ( 0 , idx):
ans + = s[i]
return ans
s = "equ#ual"
t = "gee##eeks"
if (removeBackspace(s) = = removeBackspace(t)):
print ( "TRUE" )
else :
print ( "FALSE" )
|
C#
using System;
class GFG {
static string removeBackspaces( string s)
{
int n = s.Length;
char [] ch = s.ToCharArray();
int idx = 0;
for ( int i = 0; i < n; i++) {
if (s[i] != '#' ) {
ch[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
if (idx < 0)
idx = 0;
}
s = new string (ch);
return s.Substring(0, idx);
}
public static void Main()
{
string s = "equ#ual" ;
string t = "gee##eeks" ;
if (removeBackspaces(s) == removeBackspaces(t))
Console.Write( "True" );
else
Console.Write( "False" );
}
}
|
Javascript
function removeBackspaces(s)
{
let n = s.length;
let idx = 0;
for (let i = 0; i < n; i++) {
if (s[i] != '#' ) {
s[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
if (idx < 0)
idx = 0;
}
return s.substring(0, idx);
}
let s = "equ#ual" ;
let t = "gee##eeks" ;
if (removeBackspaces(s) == removeBackspaces(t))
console.log( "True" );
else
console.log( "False" );
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach: (Using Stack)
The idea is to use a stack that stores the last occurrence of a character other than “#” (i.e, Backspace) and iterate over the each given string and if we find any character other than ‘#’ then we keep storing it into the stack otherwise remove the last occurred character which is store into the stack. Do the Similar process for both given strings and check if both strings are equal then print “Yes” otherwise “No”.
Following is the implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
string remove_backspace(string str) {
string res;
for ( char c : str) {
if (c != '#' ) {
res.push_back(c);
} else if (!res.empty()) {
res.pop_back();
}
}
return res;
}
bool compare(string s, string t) {
s = remove_backspace(s);
t = remove_backspace(t);
return s == t;
}
int main() {
string s = "geee#e#ks" ;
string t = "gee##eeks" ;
if (compare(s, t)) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}
|
Java
import java.util.*;
public class BackspaceStringCompare {
static String remove_backspace(String str) {
StringBuilder res = new StringBuilder();
for ( char c : str.toCharArray()) {
if (c != '#' ) {
res.append(c);
} else if (res.length() > 0 ) {
res.deleteCharAt(res.length() - 1 );
}
}
return res.toString();
}
static boolean compare(String s, String t) {
s = remove_backspace(s);
t = remove_backspace(t);
return s.equals(t);
}
public static void main(String[] args) {
String s = "geee#e#ks" ;
String t = "gee##eeks" ;
if (compare(s, t)) {
System.out.println( "True" );
} else {
System.out.println( "False" );
}
}
}
|
Python3
def compare(s, t):
def remove_backspace(string):
a = []
for i in string:
if i ! = "#" :
a.append(i)
else :
if len (a):
a.pop()
return "".join(a)
s, t = remove_backspace(s), remove_backspace(t)
return s = = t
s = "geee#e#ks"
t = "gee##eeks"
if (compare(s, t)):
print ( "True" )
else :
print ( "False" )
|
C#
using System;
using System.Text;
public class BackspaceStringCompare {
static string RemoveBackspace( string str) {
StringBuilder res = new StringBuilder();
foreach ( char c in str) {
if (c != '#' ) {
res.Append(c);
} else if (res.Length > 0) {
res.Remove(res.Length - 1, 1);
}
}
return res.ToString();
}
static bool Compare( string s, string t) {
s = RemoveBackspace(s);
t = RemoveBackspace(t);
return s.Equals(t);
}
public static void Main( string [] args) {
string s = "geee#e#ks" ;
string t = "gee##eeks" ;
if (Compare(s, t)) {
Console.WriteLine( "True" );
} else {
Console.WriteLine( "False" );
}
}
}
|
Javascript
function compare(s, t){
function remove_backspaces(string){
a = [];
for (let i = 0; i<string.length; i++){
if (string[i] != '#' ) a.push(string[i]);
else if (a.length > 0) a.pop();
}
return a.join( "" )
}
s = remove_backspaces(s);
t = remove_backspaces(t);
return s == t;
}
let s = "geee#e#ks" ;
let t = "gee##eeks" ;
if (compare(s,t)) console.log( "True" );
else console.log( "False" );
|
Time Complexity: O(n), Where n is the length of the given string
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...