动态规划字符串

题目

https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof

解法

从上至下dp[i] 递归分析, 从下至上 循环 解题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int translate(int num) {
if (num < 0) return -1;
String src = String.valueOf(num);
int len = src.length();
int[] dp = new int[len];
// dp[-1] = 0;
dp[0] = 1;

for (int i=1; i<len; i++) {
// dp[i] = dp[i-1] + dp[i-2];
dp[i] += dp[i-1];

String str = src.substring(i-1, i+1);
if (str.compareTo("10") >=0 && str.compareTo("25") <=0) {
if (i == 1) {
dp[i] += 1;
continue;
}
dp[i] += dp[i-2];
}
}
return dp[len-1];
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×