题目
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。
注意:如果对空文本输入退格字符,文本继续为空。
示例 1:
输入:s = "ab#c", t = "ad#c"
输出:true
解释:s 和 t 都会变成 "ac"。
示例 2:
输入:s = "ab##", t = "c#d#"
输出:true
解释:s 和 t 都会变成 ""。
解题思路
双指针,一个快指针指向字符串中的位置,一个慢指向编辑器的位置,当字符串不是退格符时,双指针同步向前移动,当字符串是退格符时,快指针继续向前,慢指针向后退。
记录下两个数组的最后慢指针位置,代表整理去除好#的数组,比较慢指针之前的数组内容。
代码
class Solution {
public:
bool backspaceCompare(string s, string t)
{
int sSlowIndex = 0;
int tSlowIndex = 0;
for (int fastIndex = 0; fastIndex < s.size(); fastIndex++)
{
if (s[fastIndex] != '#')
{
s[sSlowIndex++] = s[fastIndex];
}
else if (s[fastIndex] == '#')
{
if (sSlowIndex > 0)
{
sSlowIndex--;
}
}
}
for (int fastIndex = 0; fastIndex < t.size(); fastIndex++)
{
if (t[fastIndex] != '#')
{
t[tSlowIndex++] = t[fastIndex];
}
else if (t[fastIndex] == '#')
{
if (tSlowIndex > 0)
{
tSlowIndex--;
}
}
}
if (sSlowIndex == tSlowIndex)
{
if (sSlowIndex == 0)
{
return true;
}
else
{
for (int i = 0; i < sSlowIndex; i++)
{
if (s[i] != t[i])
{
return false;
}
}
return true;
}
}
else
return false;
}
};
11.01