01.06.字符串压缩

解题思路:

  1. 代码通俗…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String compressString(String S) {
if (S == null || S.length() <= 2) {
return S;
}
StringBuilder stringBuilder = new StringBuilder();
int cnt = 1;
stringBuilder.append(S.charAt(0));
for (int i = 1; i < S.length(); i++) {
if (S.charAt(i) == S.charAt(i - 1)) {
cnt++;
} else {
stringBuilder.append(cnt).append(S.charAt(i));
cnt = 1;
}
}
stringBuilder.append(cnt);
return stringBuilder.toString().length() > S.length() ? S : stringBuilder.toString();
}
}

98.验证二叉搜索树

解题思路:

  1. 对于二叉搜索树,左节点必须小于根,右节点必须大于根,并且每个子树也是如此。
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}

private boolean helper(TreeNode root, Integer lower, Integer upper) {
if (root == null) {
return true;
}
int val = root.val;
if ((lower != null && val <= lower) || (upper != null && val >= upper)) {
return false;
}
return helper(root.right, val, upper) && helper(root.left, lower, val);
}
}