Leetcode 844 - Backspace String Compare

Note:

  • Use stack[].

Question:

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
2
3
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var backspaceCompare = function(s, t) {
return helper(s) === helper(t);

function helper(str) {
let stack = [];
for (const ch of str) {
if (ch === '#') {
stack.pop();
continue;
}
stack.push(ch);
}
return stack.join('');
}
};