题目
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
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 <= S.length <= 200
- 1 <= T.length <= 200
- S and T only contain lowercase letters and ‘#’ characters.
Follow up:
- Can you solve it in O(N) time and O(1) space?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/backspace-string-compare
解题思路
-
方法1
- 声明一个空字符串ret_string;
- 遍历输入的字符串S;
- 遇到’#'则删除ret_string最后一个字符(ret_string为空时不操作),否则将S中当前字符添加至ret_string末尾;
- 最后比较两个输入字符串S和T通过上述步骤操作后结果是否一致。
-
方法2
- 从后往前遍历两个需要比较的字符串;
- 遇到’#‘时,需要跳过的字符个数加1;不为’#'时,判断需要跳过的字符个数是否为0,为0则跳出循环,不为0则需要跳过的字符个数减1,继续遍历;
- 当两个字符串都跳出循环时,比较两个字符串当前的字符是否一致,不一致则可判定两个字符串不相同,或一个字符串为空,而另一个字符串有值时,则也可判定两个字符串不相同;
- 若跳出循环后,两个字符串当前字符仍一致,则继续往前遍历两个字符串,重复步骤1,2,3,若两个字符串全部遍历完毕后仍一致,则可判定两个字符串相同。
算法实现(C++)
- 方法1
class Solution {
public:
bool backspaceCompare(string S, string T) {
return getFinalString(S) == getFinalString(T);
}
string getFinalString(string T)
{
string t_final;
int tSize = T.size();
for (int i = 0; i < tSize; ++i)
{
char c = T.at(i);
if (c == '#')
{
if (!t_final.empty())
t_final.pop_back();
}
else
t_final.push_back(c);
}
return t_final;
}
};
- 方法2
class Solution {
public:
bool backspaceCompare(string S, string T) {
int i = S.length() - 1;
int j = T.length() - 1;
int skipS = 0;
int skipT = 0;
while (i >= 0 || j >= 0)
{
while (i >= 0)
{
if (S[i] == '#') { --i; ++skipS; }
else if (skipS > 0) { --i; --skipS; }
else break;
}
while (j >= 0)
{
if (T[j] == '#') { --j; ++skipT; }
else if (skipT > 0) { --j; --skipT; }
else break;
}
if (i >= 0 && j >= 0 && S[i] != T[j])
return false;
if ((i >= 0) != (j >= 0))
return false;
--i;
--j;
}
return true;
}
}