leetcode-844-backspace-string-compare

Description

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:

1
2
3
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:

1
2
3
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".

Example 3:

1
2
3
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:

1
2
3
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.

Follow up:

  • Can you solve it in O(N) time and O(1)space?

####

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) {
vector<char> s1, t1;
for(int i = 0;i<S.size();i++)
{
if(S[i] == '#' && !s1.empty())
s1.pop_back();
else if(S[i] == '#' && s1.empty())
continue;
else
s1.push_back(S[i]);
}
for(int i = 0;i<T.size();i++)
{
if(T[i] == '#' && !t1.empty())
t1.pop_back();
else if(T[i] == '#' && t1.empty())
continue;
else
t1.push_back(T[i]);
}
return s1 == t1;
}

};
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×