给定 S
和 T
两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 #
代表退格字符。
注意: 如果对空文本输入退格字符,文本继续为空。
示例 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 = "#a#c"
输出:true
解释:S 和 T 都会变成 “c”。
示例 4:
输入:S = "a#c", T = "b"
输出:false
解释:S 会变成 “c”,但 T 仍然是 “b”。
提示:
1 <= S.length <= 200
1 <= T.length <= 200
S
和T
只含有小写字母以及字符'#'
。
进阶:
- 你可以用
O(N)
的时间复杂度和O(1)
的空间复杂度解决该问题吗?
代码实现
- 时间复杂度
O(N)
,空间复杂度O(N)
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def have(s1):
re = []
for i in range(len(s1)):
if s1[i]=='#':
if len(re)==0:
continue
else:
re.pop()
else:
re.append(s1[i])
return ''.join(re)
s,t = have(S), have(T)
return s==t
- 进阶
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
sl, tl = len(S)-1, len(T)-1
sc, tc = 0,0
while sl>=0 or tl>=0:
while sl>=0 and S[sl]=='#':
sl-=1
sc+=1
while tl>=0 and T[tl]=='#':
tl-=1
tc+=1
while sl>=0 and sc and S[sl]!='#':
sl-=1
sc-=1
while tl>=0 and tc and T[tl]!='#':
tl-=1
tc-=1
if sl>=0 and tl>=0:
if S[sl]!='#' and T[tl]!='#':
if S[sl]!=T[tl]: return False
sl-=1
tl-=1
if (sl>=0 and S[sl]!='#') or (tl>=0 and T[tl]!='#'):
if sl<0 or tl<0:
return False
return True
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/backspace-string-compare
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。