Backspace String Compare | Leetcode Problem Number - 844
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.
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".
Constraints:
1 <= s.length, t.length <= 200
s
andt
only contain lowercase letters and'#'
characters.
Follow up: Can you solve it in O(n)
time and O(1)
space?
class Solution {
public boolean backspaceCompare(String s, String t) {
int i = s.length()-1;
int j = t.length()-1;
int sSpaceCount = 0;
int tSpaceCount = 0;
// While there may be char in String S or String T
while(i >= 0 || j >= 0) {
// Find position of next powssible char in String S
while(i >=0 ) {
if(s.charAt(i) == '#') {
sSpaceCount++;
i--;
} else if(sSpaceCount > 0) {
sSpaceCount--;
i--;
}
else
break;
}
// Find position of next powssible char in String T
while(j >=0 ) {
if(t.charAt(j) == '#'){
tSpaceCount++;
j--;
} else if(tSpaceCount > 0){
tSpaceCount--;
j--;
} else
break;
}
System.out.println(i+" "+j);
// If any of the index is negative, then both the strings are not same.
if(i>=0 != j>=0)
return false;
// If both the index are valid and their characters are not same, then they are not in match
if( i>=0 && j>=0 && s.charAt(i) != t.charAt(j))
return false;
i--;
j--;
}
return true;
}
}