1
+ /* **************************************************************************
2
+ * Copyright 2024 The OpenGenus.org Authors. All Rights Reserved.
3
+ *
4
+ * Code for the book "DAILY 43: Algorithmic Problems for Coding Interviews: Easy level, C++ edition"
5
+ *
6
+ * Licensed under the GNU General Public License, Version 3.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.gnu.org/licenses/gpl-3.0.html
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ *
18
+ * For details about the book, please visit: https://www.amazon.com/dp/B0CZJNBLQS
19
+ * *************************************************************************/
20
+
21
+ #include < iostream>
22
+ #include < stack>
23
+ #include < string>
24
+
25
+ class Solution {
26
+ public:
27
+ bool backspaceCompare (std::string S, std::string T) {
28
+ std::stack<int > s1, s2;
29
+ std::string str1, str2;
30
+ for (int i = 0 ; i < S.size (); i++) {
31
+ if (S[i] == ' #' && !s1.empty ())
32
+ s1.pop ();
33
+ else if (S[i] != ' #' )
34
+ s1.push (S[i]);
35
+ }
36
+ for (int i = 0 ; i < T.size (); i++) {
37
+ if (T[i] == ' #' && !s2.empty ())
38
+ s2.pop ();
39
+ else if (T[i] != ' #' )
40
+ s2.push (T[i]);
41
+ }
42
+ while (!s1.empty ()) {
43
+ str1.push_back (s1.top ());
44
+ s1.pop ();
45
+ }
46
+ while (!s2.empty ()) {
47
+ str2.push_back (s2.top ());
48
+ s2.pop ();
49
+ }
50
+ return str1 == str2;
51
+ }
52
+ };
53
+
54
+ int main () {
55
+ Solution sol;
56
+ std::string S1 = " ab#c" , T1 = " ad#c" ; // true
57
+ std::string S2 = " ab##" , T2 = " c#d#" ; // true
58
+ std::string S3 = " a##c" , T3 = " #a#c" ; // true
59
+ std::string S4 = " a#c" , T4 = " b" ; // false
60
+
61
+ std::cout << " S: " << S1 << " , T: " << T1 << " -> " << (sol.backspaceCompare (S1, T1) ? " true" : " false" ) << std::endl;
62
+ std::cout << " S: " << S2 << " , T: " << T2 << " -> " << (sol.backspaceCompare (S2, T2) ? " true" : " false" ) << std::endl;
63
+ std::cout << " S: " << S3 << " , T: " << T3 << " -> " << (sol.backspaceCompare (S3, T3) ? " true" : " false" ) << std::endl;
64
+ std::cout << " S: " << S4 << " , T: " << T4 << " -> " << (sol.backspaceCompare (S4, T4) ? " true" : " false" ) << std::endl;
65
+
66
+ return 0 ;
67
+ }
0 commit comments