[JS] Backspace String Compare
2022. 8. 7. 12:38
🔒 문제 (LeetCode 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.
Constraints:
- 1 <= s.length, t.length <= 200
- s and t only contain lowercase letters and '#' characters.
Follow up: Can you solve it in O(n) time and O(1) space?
🌊 입출력
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".
🔑 해결
🌌 알고리즘 - 스택
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var backspaceCompare = function(s, t) {
const [stack1, stack2] = [[], []];
const makeString = (stack, str) => {
for(let i = 0; i < str.length; i++) {
if(str[i] !== '#') stack.push(str[i]);
else if(stack.length && str[i] === '#') stack.pop();
}
return stack.join();
}
return makeString(stack1, s) === makeString(stack2, t)
};
'코딩테스트 (JS) > 스택 | 큐' 카테고리의 다른 글
[JS] 괄호 회전하기 (0) | 2022.11.16 |
---|---|
[JS] 110 옮기기 (0) | 2022.07.21 |
[JS] 큰 수 만들기 (0) | 2022.06.09 |