1. 程式人生 > >844. Backspace String Compare

844. Backspace String Compare

數量 操作 urn 是否 HA tex style The 說明

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 };

844. Backspace String Compare