-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP331.cpp
51 lines (49 loc) · 1.16 KB
/
P331.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
#include "header.h"
class Solution {
int getNum(const string &s, int p, int &num) {
while (p<s.length() && s[p]==' ') p++;
if (s[p]=='#') return 0;
num = 0;
int i=p;
while (i<s.length() && s[i]!=',')
{
num = num*10 + (s[i]-'0');
i++;
}
return i-p;
}
public:
bool isValidSerialization(string preorder) {
int i=0;
int id = 0;
while (i<preorder.length())
{
int len, num, k;
len = getNum(preorder, i, num);
i+=len;
if (len>0) {
id++;
}
else {
i++;
if (id>0)
id--;
else
break;
}
i += 1;
}
// printf("%d\n", i);
return i==preorder.length() && id==0;
}
};
int main() {
string s;
s = "9,3,4,#,#,1,#,#,2,#,6,#,#";
cout << Solution().isValidSerialization(s) << endl;
s = "1,#";
cout << Solution().isValidSerialization(s) << endl;
s = "9,#,#,1";
cout << Solution().isValidSerialization(s) << endl;
return 0;
}