36.5k views
4 votes
Write a function called backspaceCompare that takes two strings sl and s2 and evaluate them when both are typed into empty text editors. (# means a backspace character). backspacecompare should return true if the evaluated strings are equal or false if they are not equal. You should make use of the built-in java implementation of the stack data structure under java.util.Stack . (assume that the user inputs correct strings)

Example 1:
Input : s1 = "Datastructure sissss###Fun", s2 = "Datastructures Iszwp###Fun"
Output: true
Explanation: Both s1 and s2 become "DataStructuresIsFun".
Example 2:
Input : S = "abc##, T = "wc#d#"
Output: false
Explanation: s1 becomes "a" while s2 becomes "w"
Function Template
import java.util.Stack;
public class Lab3 {
public static void main (String[] args) {
String s1 = "Dat astructure sissss###Fun";
String s2 = "Dat astructure s1szwp###Fun";
boolean ans = backspaceCompare(s1, s2);
System.out.println (ans); // Should be True
}
public static boolean backspaceCompare(String s1, String s2) {
Stack s1 stack = new Stack();
Stack s2 stack = new Stack();
// Example of push stack.push("D")
// Example of peek stack.peek()
// Example of pop stack.pop()
// Example of İsEmpty stack. isEmpty()
// INSERT YOUR CODE HERE
}
}

1 Answer

2 votes

Answer:

Go to explaination for the program code

Step-by-step 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;

}

}

User Kkmishra
by
4.1k points