1.题目描述
844.比较含退格的字符串
【简单】
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。
注意:如果对空文本输入退格字符,文本继续为空。
示例 1:
输入:s = "ab#c", t = "ad#c"
输出:true
解释:s 和 t 都会变成 "ac"。
示例 2:
输入:s = "ab##", t = "c#d#"
输出:true
解释:s 和 t 都会变成 ""。
示例 3:
输入:s = "a#c", t = "b"
输出:false
解释:s 会变成 "c",但 t 仍然是 "b"。
提示:
1 <= s.length, t.length <= 200
s 和 t 只含有小写字母以及字符 '#'
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/backspace-string-compare
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码
class Solution {
public:
bool backspaceCompare(string s, string t) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < s.size(); fastIndex++) {
if (s[fastIndex] != '#') {
s[slowIndex++] = s[fastIndex];
} else {
if (slowIndex > 0) slowIndex--;
}
}
int slowIndex1 = 0;
for (int fastIndex = 0; fastIndex < t.size(); fastIndex++) {
if (t[fastIndex] != '#') {
t[slowIndex1++] = t[fastIndex];
} else {
if (slowIndex1 > 0) slowIndex1--;
}
}
if (slowIndex != slowIndex1) {
return false;
} else {
for (int i = 0; i < slowIndex; i++) {
if(s[i] != t[i]) {
return false;
}
}
return true;
}
}
};
仅记录,侵权删