比较含退格的字符串
LeetCode传送门 844. Backspace String Compare
题目
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,请你判断二者是否相等。# 代表退格字符。
如果相等,返回 true ;否则,返回 false 。
注意:如果对空文本输入退格字符,文本继续为空。
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 :
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Input: s = "a##c", t = "#a#c"
Output: true
Explanation: Both s and t become "c".
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
Constraints:
- 1 <= s.length, t.length <= 200
- s and t only contain lowercase letters and '#' characters.
思考线
解题思路
看到这道题,我们先看除了要处理小写字符之外我们还需要做什么呢?就是处理特殊字符#。而#是一个删除操作,删除上一个字符。
那么我们该怎么去处理这个特殊操作呢?
我们使用 stack这种数据结构来保存处理掉特殊字符后的数据。因为栈具有典型的FILO特性。能很好的保存题目中的字符。
那么我们先对 s和 t进行循环操作。若
- 遍历到字符,直接
push到 对应的stack - 遍历到
#, 执行stack.pop()
综上,我们在敲代码的时候就下手如有神。
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var backspaceCompare = function (s, t) {
const sStack = [];
const tStack = []
for (let i = 0; i < s.length; i++) {
if (s[i] === '#') {
sStack.length && sStack.pop();
} else {
sStack.push(s[i]);
}
}
for (let j = 0; j < t.length; j++) {
if (t[j] === '#') {
tStack.length && tStack.pop()
} else {
tStack.push(t[j])
}
}
return sStack.join('') === tStack.join('');
};
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。