46.把数字翻译成字符串
大约 1 分钟
46.把数字翻译成字符串
参考链接
剑指 Offer 46. 把数字翻译成字符串-跟着帅地玩转校招,刷爆各类算法题帅地玩Offer
优秀题解
class Solution {
public int crackNumber(int ciphertext) {
String s = String.valueOf(ciphertext);
int a = 1, b = 1;
for(int i = 2; i <= s.length(); i++) {
String tmp = s.substring(i - 2, i);
int c = tmp.compareTo("10") >= 0 && tmp.compareTo("25") <= 0 ? a + b : a;
b = a;
a = c;
}
return a;
}
}
作者:Krahets
链接:https://leetcode.cn/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/solutions/199945/mian-shi-ti-46-ba-shu-zi-fan-yi-cheng-zi-fu-chua-6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
转移方程:
xn-1 与 xn 不可搭配,复制 dp[n - 1]
xn-1 与 xn 可搭配,可以有两种选择,搭配则复制dp[j - 2],不搭配则复制dp[i - 1] $$ dp[n] = \begin{cases} dp[n - 1], & x_{n - 1} 与 x_{n} 不可搭配 \ dp[n - 2] + dp[n - 1], & x_{n - 1} 与 x_{n} 可搭配 \end{cases} $$
$i / x_i$ | 0 | 1 | 2 | 3 | 4 | 5 | |
---|---|---|---|---|---|---|---|
nums[i] | '2' | '1' | '6' | '6' | '1' | '2' | |
$j$ | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
dp[j] | 1 | 1 | 1+1=2 | 2+1=3 | 3 | 3 | 3+3=6 |