Skip to content

Commit 6fe551f

Browse files
committed
20190127
1 parent 897e00e commit 6fe551f

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

code/lc108.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package code;
2+
/*
3+
* 108. Convert Sorted Array to Binary Search Tree
4+
* 题意:将有序数组转换为二叉平衡树
5+
* 难度:Easy
6+
* 分类:Tree, Depth-first Search
7+
* 思路:类似二分查找,每次把数组劈成两半
8+
* Tips:Bingo!
9+
*/
10+
public class lc108 {
11+
public class TreeNode {
12+
int val;
13+
TreeNode left;
14+
TreeNode right;
15+
TreeNode(int x) { val = x; }
16+
}
17+
public TreeNode sortedArrayToBST(int[] nums) {
18+
TreeNode tn = helper(nums, 0, nums.length-1);
19+
return tn;
20+
}
21+
public TreeNode helper(int[] nums, int left, int right){
22+
if(left<right) return null;
23+
int mid = (left+right)/2;
24+
TreeNode tn = new TreeNode(nums[mid]);
25+
tn.left = helper(nums, left, mid-1);
26+
tn.right = helper(nums, mid+1, right);
27+
return tn;
28+
}
29+
}

code/lc91.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package code;
2+
/*
3+
* 91. Decode Ways
4+
* 题意:1~26代表了26个字母
5+
* 难度:Medium
6+
* 分类:String, Dynamic Programming
7+
* 思路:动态规划,和上台阶问题很像
8+
* Tips:Bingo!
9+
*/
10+
public class lc91 {
11+
public static void main(String[] args) {
12+
System.out.println(numDecodings("99"));
13+
}
14+
public static int numDecodings(String s) {
15+
if(s.length()==0) return 0;
16+
int[] dp = new int[s.length()+1];
17+
dp[0] = 1;
18+
int ch = s.charAt(0)-'0';
19+
if( ch<1 || ch>9 ) return 0; //判断第一个字符是否符合规范
20+
else dp[1] = 1;
21+
for (int i = 2; i < s.length()+1 ; i++) {
22+
int a = s.charAt(i-2)-'0';
23+
int b = s.charAt(i-1)-'0';
24+
if( (a*10+b)<=26 && (a*10+b)>=10 ) //可能存在两个字符10符合,但一个字符0不符合的情况,所以+=
25+
dp[i] += dp[i-2];
26+
if( b>0 && b<=9 )
27+
dp[i] += dp[i-1];
28+
if(dp[i]==0) return 0; //解析错误
29+
}
30+
return dp[s.length()];
31+
}
32+
}

0 commit comments

Comments
 (0)