Sitemap

844. Backspace String Compare LeetCode Problem (Java)

1 min readOct 19, 2023

--

Problem Statement: 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.

hint: Stack or StringBuilder or Two Pointers or arrays.

Get Soham’s stories in your inbox

Join Medium for free to get updates from this writer.

Constraints:

  • 1 <= s.length, t.length <= 200
  • s and t only contain lowercase letters and '#' characters.

Example 1:

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Example 2:

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Example 3:

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".

Solution:

class Solution {
public boolean backspaceCompare(String s, String t) {
Stack<Character> stk1=new Stack<>();
Stack<Character> stk2=new Stack<>();
for(char c:s.toCharArray()){
if(c!='#')
stk1.push(c);
else
if(!stk1.isEmpty()) stk1.pop();
}
for(char c:t.toCharArray()){
if(c!='#')
stk2.push(c);
else
if(!stk2.isEmpty()) stk2.pop();
}
if(stk1.equals(stk2)) return true;
return false;
}
}

--

--