Answer:
Go to explaination for the program code
Explanation:
import java.util.Stack;
public class Lab3 {
public static void main(String[] args) {
String s1="DataStructuresIssss###Fun";
String s2="DataStructuresIszwp###Fun";
boolean ans=backspaceCompare(s1,s2);
System.out.println(ans);
/*String s1="abc##";
String s2="wc#d#";
boolean ans=backspaceCompare(s1,s2);
System.out.println(ans);*/
}
public static boolean backspaceCompare(String s1, String s2) {
Stack<Character> s1_stack=new Stack<Character>();
Stack<Character> s2_stack=new Stack<Character>();
//backspaceCount is a variable to count back space
int backspaceCount=0;
//logic is that if '#' encountered we are putting pop else push
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)=='#'){
backspaceCount++;
s1_stack.pop();
}
else
{
s1_stack.push(s1.charAt(i));
}
}
//this all is for s2 string
for(int i=0;i<s2.length();i++){
if(s2.charAt(i)=='#') s2_stack.pop();
else s2_stack.push(s2.charAt(i));
}
//here is the main logic first we are adding based upon # means we pop up the string while adding the string if any # character found
//here we are checking from the end using pop condition both are not mathing then we are returning false
for(int i=0;i<s1.length()-2*backspaceCount;i++){
if(s1_stack.pop()!=s2_stack.pop()) return false;
}
return true;
}
}