Skip to content

Instantly share code, notes, and snippets.

@jinzhubaofu
Last active August 29, 2015 14:13
Show Gist options
  • Save jinzhubaofu/9b7c7f352e67113dd835 to your computer and use it in GitHub Desktop.
Save jinzhubaofu/9b7c7f352e67113dd835 to your computer and use it in GitHub Desktop.
leetcode solutions
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
int left = 0;
int right = 0;
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
if (root.left != null) {
left = this.maxDepth(root.left);
}
if (root.right != null) {
right = this.maxDepth(root.right);
}
return 1 + (left > right ? left : right);
}
}
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (int i = 0, len = s.length(); i < len; i++) {
result *= 26;
result += s.charAt(i) - 'A' + 1;
}
return result;
}
}
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (string::iterator i = s.begin(); i != s.end(); ++i) {
switch (*i) {
case 40:
stk.push(41);
break;
case 123:
stk.push(125);
break;
case 91:
stk.push(93);
break;
case 41: case 125: case 93:
if (stk.empty()) {
return false;
}
int top = stk.top();
if (top != *i) {
return false;
}
stk.pop();
}
}
return stk.empty();
}
};
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if (m > 0 && n == 0) {
return;
}
if (m == 0 && n > 0) {
while (n >= 0) {
A[--n] = B[n];
}
return;
}
int total = m + n;
int tmp[total];
for (int i = 0, j = 0; i + j < total;) {
if (i == m) {
tmp[i + j] = B[j++];
continue;
}
if (j == n) {
tmp[i + j] = A[i++];
continue;
}
if (A[i] < B[j]) {
tmp[i + j] = A[i++];
}
else {
tmp[i + j] = B[j++];
}
}
for (int i = 0; i < total; i++) {
A[i] = tmp[i];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment