https://leetcode.com/problems/backspace-string-compare/
- Stack
- String
Simulate backspace processing using two pointers from the end for O(1) space.
O(n + m)
O(1)
class Solution {
private int nextValid(String s, int i) {
int skip = 0;
while (i >= 0) {
if (s.charAt(i) == '#') skip++;
else if (skip > 0) skip--;
else break;
i--;
}
return i;
}
public boolean backspaceCompare(String s, String t) {
int i = s.length() - 1, j = t.length() - 1;
while (i >= 0 || j >= 0) {
i = nextValid(s, i);
j = nextValid(t, j);
if (i < 0 || j < 0) return i == j;
if (s.charAt(i) != t.charAt(j)) return false;
i--;
j--;
}
return true;
}
}