码迷,mamicode.com
首页 > 其他好文 > 详细

844. Backspace String Compare

时间:2018-06-09 14:35:55      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:col   str   模拟   记录   方案   Plan   ati   pac   editor   

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

标签:col   str   模拟   记录   方案   Plan   ati   pac   editor   

原文地址:https://www.cnblogs.com/Zzz-y/p/9159210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!