Back to Dashboard
Comparing Strings containing Backspaces
MediumProblem Statement
Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.
Examples
Example 1:
- Input:
s = "ab#c", t = "ad#c" - Output:
true
Approach 1: Two Pointers
O(n)
O(1)
class Solution {
public boolean backspaceCompare(String s, String t) {
var i1 = s.length() - 1;
var i2 = t.length() - 1;
while (i1 >= 0 || i2 >= 0) {
var p1 = findIndexAfterBackSpace(s, i1);
var p2 = findIndexAfterBackSpace(t, i2);
if (p1 < 0 && p2 < 0) {
return true;
}
if (p1 < 0 || p2 < 0) {
return false;
}
if (s.charAt(p1) != t.charAt(p2)) {
return false;
}
i1 = p1 - 1;
i2 = p2 - 1;
}
return true;
}
private int findIndexAfterBackSpace(String s, int i) {
var bp = 0;
while (i >= 0) {
if (s.charAt(i) == '#') {
bp ++;
} else if (bp > 0) {
bp --;
} else {
break;
}
i --;
}
return i;
}
}