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.

  • Can you solve it in O(N) time and O(1) space?
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

两个字符串,‘#’表示退格,判断字符串最后是否相同。

解决方案主要是模拟一下退格操作就可以了。

用两个变量分别记录S和T中的退格数量,依次删除前面的字符,直到无法退格,并比较对应的字符。

当对应比较的字符不相等,或者S/T还有字符但T/S已经没有字符待比较,说明两者不同。

 1 class Solution {
 2 public:
 3     bool backspaceCompare(string S, string T) {
 4         int s = 0;
 5         int t = 0;
 6         int i = S.size() - 1;
 7         int j = T.size() - 1;
 8         while (i >= 0 || j >= 0) {
 9             while (i >= 0 && (s > 0 || S[i] == '#')) {
10                 if (S[i] == '#')
11                     ++s;
12                 else
13                     --s;
14                 --i;
15             }
16             while (j >= 0 && (t > 0 || T[j] == '#')) {
17                 if (T[j] == '#')
18                     ++t;
19                 else
20                     --t;
21                 --j;
22             }
23             if (i >= 0 && j >= 0) {
24                 if (S[i] != T[j])
25                     return false;
26                 --i;
27                 --j;
28             }
29             else if (i >= 0 || j >= 0)
30                 return false;
31         }
32         return true;
33     }
34 };

猜你喜欢

转载自www.cnblogs.com/Zzz-y/p/9159210.html