Skip to content

Commit b6d9ae5

Browse files
committed
add prob #844; O(N) in time and O(1) in space;
1 parent 89df565 commit b6d9ae5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

844_Backspace_String_Compare_2nd.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/* O(N) in time and O(1) in space */
2+
#include <string>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
bool backspaceCompare(string S, string T) {
8+
int i = S.size() - 1;
9+
int j = T.size() - 1;
10+
while(true){
11+
int bcnt = 0;
12+
while( (i>=0)&&( (S[i]=='#')||(bcnt>0) ) ){
13+
if(S[i]=='#') ++bcnt;
14+
else --bcnt;
15+
--i;
16+
}
17+
bcnt = 0;
18+
while( (j>=0)&&( (T[j]=='#')||(bcnt>0) ) ){
19+
if(T[j]=='#') ++bcnt;
20+
else --bcnt;
21+
--j;
22+
}
23+
24+
if( (i<0)&&(j<0) ) break;
25+
else if(i<0) return false;
26+
else if(j<0) return false;
27+
else if(S[i]==T[j]){
28+
--i; --j;
29+
}
30+
else return false;
31+
}
32+
return true;
33+
}
34+
};

0 commit comments

Comments
 (0)