844. Backspace String Compare
202410032305
tags: #two-pointers
const getNextValidCharIndex = (str, end) => {
let backspaceCount = 0;
while (end >= 0) {
if (str[end] === '#') {
backspaceCount += 1;
}
else if (backspaceCount > 0) {
backspaceCount -= 1;
}
else if (str[end] !== '#') {
break;
}
end -= 1;
}
return end;
}
var backspaceCompare = function(s, t) {
let idxS = s.length - 1;
let idxT = t.length - 1;
while (idxS >= 0 || idxT >= 0) {
idxS = getNextValidCharIndex(s, idxS);
idxT = getNextValidCharIndex(t, idxT);
if (idxS < 0 && idxT < 0) {
return true;
}
if (idxS < 0 || idxT < 0) {
return false;
}
if (s[idxS] != t[idxT]) {
return false;
}
idxS -= 1;
idxT -= 1;
}
return true;
};