-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path331.cpp
39 lines (38 loc) · 822 Bytes
/
331.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
// better.cpp
class Solution {
public:
bool isValidSerialization(string preorder) {
stringstream ss(preorder);
string str;
int num = 0;
while (!ss.eof()) {
getline(ss, str, ',');
num += str == "#" ? -1 : 1;
if (num == -1)
break;
}
return num == -1 && ss.eof();
}
};
// dfs+stringstream.cpp
class Solution2 {
bool dfs(vector<string> &arr, int &i) {
if (i >= arr.size())
return false;
if (arr[i] == "#")
return true;
return dfs(arr, ++i) && dfs(arr, ++i);
}
public:
bool isValidSerialization(string preorder) {
vector<string> arr;
stringstream ss(preorder);
string str;
while (!ss.eof()) {
getline(ss, str, ',');
arr.emplace_back(str);
}
int i = 0;
return dfs(arr, i) && i == arr.size() - 1;
}
};