题目描述:
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 = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1. 1 <= S.length <= 200
2. 1 <= T.length <= 200
3. S and T only contain lowercase letters and '#' characters.
Follow up: Can you solve it in O(N) time and O(1) space?
class Solution {
public:
bool backspaceCompare(string S, string T) {
int i=0;
int j=0;
while(j<S.size())
{
if(S[j]=='#')
{
if(i>0) i--;
}
else
{
S[i]=S[j];
i++;
}
j++;
}
//S[i]=S[j]时,i++,此时i就是字符串长度
int length_s=i;
i=0;
j=0;
while(j<T.size())
{
if(T[j]=='#')
{
if(i>0) i--;
}
else
{
T[i]=T[j];
i++;
}
j++;
}
int length_t=i;
return S.substr(0,length_s)==T.substr(0,length_t);
}
};
本文探讨了在存在退格字符的情况下,两个字符串的比较算法。通过实例展示了如何处理特殊字符,实现字符串的有效对比。文章深入解析了算法的时间和空间复杂度,并提出了一种O(N)时间O(1)空间的解决方案。
454

被折叠的 条评论
为什么被折叠?



