844 Backspace String Compare [难度:简单] [空间复杂度为1|巧妙运用变量]
【题目】
Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S
andT
only contain lowercase letters and'#'
characters.
Follow up:
Can you solve it in O(N)
time and O(1)
space?
【解题C++】
先放个时间复杂度O(N)空间复杂度也O(N)的常规思路吧
class Solution {
public:
//函数返回类型是栈不能只写Stack哈~
stack<char> getStack(string tmp)
{
stack<char> st0;
for(int i=0;i<tmp.size();i++)
{
//如果碰到了#且栈不为空,删除
if(tmp[i]=='#'&&!st0.empty())
st0.pop();
//这里不能else,必须加上判断条件,不然碰到#但栈为空的情况也会归类到此处
else if(tmp[i]!='#')
st0.push(tmp[i]);
}
return st0;
}
bool backspaceCompare(string S, string T) {
stack<char> st1,st2;
st1 = getStack(S);
st2 = getStack(T);
//栈可以直接进行比较
return st1==st2;
}
};
空间复杂度为1是在评论区参考的大神解法。
基本思路是,从后往前比较字符,并用一个变量存储需要删除的次数。具体写注释里。
class Solution {
public:
bool backspaceCompare(string S, string T) {
int cnt1 = 0,cnt2 = 0;
int i = S.size()-1,j = T.size()-1;
//至少有一个字符串还没走到底
while(i>=0||j>=0)
{
//先看第一个字符串
while(i>=0)
{
//如果遇到了#
if(S[i]=='#')
{
//往前走一步
i--;
//并让记录删除个数的变量自增
cnt1++;
}
//如果是普通字母,并且前面遇到过#
else if(S[i]!='#'&&cnt1>0)
{
//往前走
i--;
//删除当前字符后得自减
cnt1--;
}
//在该字符串遍历完(i>=0)||目前暂时没有要删除的字母
else break;
}
while(j>=0)
{
if(T[j]=='#')
{
j--;
cnt2++;
}
else if(T[j]!='#'&&cnt2>0)
{
j--;
cnt2--;
}
else break;
}
//特殊情况:比如a#和a
if((i>=0&&j<0)||(i<0&&j>=0))
return false;
//如果进行了一次删除后,此时两字母不相等,返回false
if(i>=0&&j>=0&&S[i]!=T[j])
return false;
//继续自减,进行下一次循环,也就是下一次删除
i--;
j--;
}
return true;
}
};
【解题Python】
思路同C++。
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
i,j = len(S)-1,len(T)-1
cnt1 = cnt2 = 0
while i>=0 or j>=0:
while i>=0:
if S[i]=='#':
i -= 1
cnt1 += 1
elif S[i]!='#' and cnt1>0:
cnt1 -= 1
i -= 1
else:
break
while j>=0:
if T[j]=='#':
j -= 1
cnt2 += 1
elif T[j]!='#' and cnt2>0:
j -= 1
cnt2 -= 1
else:
break
if (i>=0 and j<0) or (i<0 and j>=0):
return False
if i>=0 and j>=0 and S[i]!=T[j]:
return False
i -= 1
j -= 1
return True