Skip to content

Commit 2027716

Browse files
committed
add prob #331(2nd); O(N) in time and O(1) in space;
1 parent b6d9ae5 commit 2027716

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 isValidSerialization(string preorder) {
8+
if(preorder.empty()) return false;
9+
int res = 1;
10+
11+
int i=0;
12+
while(i<(int)preorder.size()){
13+
while( (i<(int)preorder.size())&&(preorder[i]!=',') ){
14+
++i;
15+
}
16+
if(preorder[i-1]=='#'){
17+
--res;
18+
}
19+
else{
20+
++res;
21+
}
22+
23+
if( (i<(int)preorder.size())&&(res==0) ){
24+
return false;
25+
}
26+
++i;
27+
}
28+
29+
return res==0;
30+
}
31+
};

0 commit comments

Comments
 (0)