844. Backspace String Compare
题目
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 <= 200
1 <= T.length <= 200
S
andT
only contain lowercase letters and'#'
characters.
解决
假设字符串S
和T
长度最大为n
。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
class Solution {
public:
bool backspaceCompare(string S, string T) {
string s = build(S);
string t = build(T);
return (s == t);
}
string build(string & a) {
string::iterator it = a.begin();
while (it != a.end()) {
if ((*it) == '#') {
if (it == a.begin()) {
it = a.erase(it);
} else {
it = a.erase(it) - 1;
it = a.erase(it);
}
} else {
it++;
}
}
string result = a;
return result;
}
};