Skip to content

Commit 7baa429

Browse files
committed
2 problems
1 parent 541086c commit 7baa429

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
213213
#### [290. Word Pattern](https://github.com/hitzzc/go-leetcode/tree/master/word_pattern)
214214
#### [292. Nim Game](https://github.com/hitzzc/go-leetcode/tree/master/nim_game)
215215
#### [295. Find Median from Data Stream](https://github.com/hitzzc/go-leetcode/tree/master/find_median_from_data_stream)
216+
#### [297. Serialize and Deserialize Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/serialize_and_deserialize_binary_tree)
217+
#### [299. Bulls and Cows](https://github.com/hitzzc/go-leetcode/tree/master/bulls_and_cows)
216218

217219

218220

bulls_and_cows/bulls_and_cows.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <string>
2+
using namespace std;
3+
4+
class Solution {
5+
public:
6+
string getHint(string secret, string guess) {
7+
int secret_array[10] = {0};
8+
int bull = 0;
9+
for (int i = 0; i < secret.size(); ++i) {
10+
if (secret[i] == guess[i]) {
11+
++bull;
12+
continue;
13+
}
14+
++secret_array[secret[i]-'0'];
15+
}
16+
int cow = 0;
17+
for (int i = 0; i < guess.size(); ++i) {
18+
if (secret[i] == guess[i]) {
19+
continue;
20+
}
21+
if (secret_array[guess[i]-'0'] !=0 ){
22+
++cow;
23+
--secret_array[guess[i]-'0'];
24+
}
25+
}
26+
return to_string(bull) + "A" + to_string(cow) + "B";
27+
}
28+
};
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <string>
2+
using namespace std;
3+
4+
struct TreeNode {
5+
int val;
6+
TreeNode *left;
7+
TreeNode *right;
8+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9+
};
10+
11+
class Codec {
12+
public:
13+
string serialize(TreeNode* root) {
14+
if (root == NULL) {
15+
return "null";
16+
}
17+
string ret = to_string(root->val);
18+
ret += "," + serialize(root->left);
19+
ret += "," + serialize(root->right);
20+
return ret;
21+
}
22+
23+
TreeNode* deserialize(string data) {
24+
int idx = 0;
25+
return helper(data, idx);
26+
}
27+
28+
TreeNode* helper(string& data, int& idx) {
29+
int start = idx;
30+
for (; idx < data.size(); ++idx) {
31+
if (data[idx] == ',') {
32+
break;
33+
}
34+
}
35+
string sub = data.substr(start, idx-start);
36+
++idx;
37+
if (sub == "null") return NULL;
38+
TreeNode* node = new TreeNode(stoi(sub));
39+
if (idx == data.size()) return node;
40+
node->left = helper(data, idx);
41+
node->right = helper(data, idx);
42+
return node;
43+
}
44+
};

0 commit comments

Comments
 (0)