-
Notifications
You must be signed in to change notification settings - Fork 25
/
Backspace_String_Compare.cpp
57 lines (49 loc) · 1.26 KB
/
Backspace_String_Compare.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;
#define ll long long
/*Given two strings s and t,
return true if they are equal
when both are typed into empty text editors.
'#' means a backspace character.
Note that after backspacing an empty text,
the text will continue empty.
Example 1:
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
*/
class Solution {
public:
bool backspaceCompare(string s, string t) {
stack<char > s1, t1;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '#' && !s1.empty()) {
s1.pop();
}
else if (s[i] != '#') {
s1.push(s[i]);
}
}
for (int i = 0; i < t.size(); ++i) {
if (t[i] == '#' && !t1.empty()) {
t1.pop();
}
else if (t[i] != '#') {
t1.push(t[i]);
}
}
while (!s1.empty() && !t1.empty()) {
if (s1.top() != t1.top()) return false;
else s1.pop(), t1.pop();
}
if (s1.empty() && t1.empty()) return true;
else return false;
}
};
int main() {
string s, t;
cin >> s >> t;
Solution ob;
cout << ob.backspaceCompare(s, t) << '\n';
return 0;
}