O(n) time O(1) space
从后往前扫,遇到#就处理,直到两个字符串都扫完
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: bool backspaceCompare(string S, string T) { int m = S.length(), n = T.length(); int i = m - 1, j = n - 1; for (; i >= 0 || j >= 0; --i, --j) { resolve(S, i); resolve(T, j); if (i < 0 || j < 0 || S[i] != T[j]) break; } return i < 0 && j < 0; }
void resolve(const string &s, int &i) { for (int cnt = 0; i >= 0; --i) { cnt += s[i] == '#' ? 1 : -1; if (cnt < 0) return; } } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public: bool backspaceCompare(string S, string T) { int m = S.length(), n = T.length(); int i = m - 1, j = n - 1; for (; i >= 0 || j >= 0; --i, --j) { resolve(S, i); resolve(T, j); if (i < 0 || j < 0 || S[i] != T[j]) break; } return i < 0 && j < 0; }
void resolve(const string &s, int &i) { int cnt = 0; while (i >= 0 && s[i] == '#') { while (i >= 0 && s[i] == '#') { ++cnt; --i; } while (i >= 0 && s[i] != '#' && cnt-- > 0) { --i; } } } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: bool backspaceCompare(string S, string T) { while (!S.empty() || !T.empty()) { resolve(S); resolve(T); if (S.empty() || T.empty() || S.back() != T.back()) break; S.pop_back(); T.pop_back(); } return S.empty() && T.empty(); }
void resolve(string &s) { int cnt = 0; while (!s.empty() && s.back() == '#') { while (!s.empty() && s.back() == '#') { ++cnt; s.pop_back(); } while (!s.empty() && s.back() != '#' && cnt > 0) { s.pop_back(); --cnt; } } } };
|