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 <= S.length <= 2001 <= T.length <= 200SandTonly contain lowercase letters and'#'characters.
Follow up:
- Can you solve it in
O(N)time andO(1)space?
Update the S and T to the results of applying backspaces, then compare the strings.
// OJ: https://leetcode.com/problems/backspace-string-compare/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
string normalize(string &s) {
int len = 0;
for (char c : s) {
if (c == '#') len = max(len - 1, 0);
else s[len++] = c;
}
s.resize(len);
return s;
}
public:
bool backspaceCompare(string S, string T) {
return normalize(S) == normalize(T);
}
};If it's not allowed to change the input string, we scan backward. back function is used to skip all characters that are deleted using backspaces. After back, the indexes are pointing to characters that we need to compare.
// OJ: https://leetcode.com/problems/backspace-string-compare/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
void back(string &s, int &i) {
if (i < 0 || s[i] != '#') return;
int cnt = 0;
for (; i >= 0 && (cnt || s[i] == '#'); --i) {
if (s[i] == '#') ++cnt;
else --cnt;
}
}
public:
bool backspaceCompare(string S, string T) {
int i = S.size() - 1, j = T.size() - 1;
while (i >= 0 || j >= 0) {
back(S, i);
back(T, j);
if ((i >= 0 && j < 0) || (i < 0 && j >= 0)) return false;
for (; i >= 0 && j >= 0 && S[i] != '#' && T[j] != '#'; --i, --j) {
if (S[i] != T[j]) return false;
}
}
return true;
}
};