Medium
看了一下一刷时间是一个半月前,第二次自己没做出来。属于一看答案就很清楚怎么做但自己主动做还是困难的那种。
class Solution {
//pay attention to these testcases:
//"01"
//"10"
public int numDecodings(String s) {
if (s == null || s.length() == 0){
return 0;
}
int[] dp = new int[s.length() + 1];
dp[0] = 1;
if (s.charAt(0) != '0'){
dp[1] = 1;
}
for (int i = 2; i <= s.length(); i++){
int num = Integer.parseInt(s.substring(i - 1, i));
if (num >= 1 && num <= 9){
dp[i] += dp[i - 1];
}
num = Integer.parseInt(s.substring(i - 2, i));
if (num >= 10 && num <= 26){
dp[i] += dp[i - 2];
}
}
return dp[s.length()];
}
}
这道题一般会有一个 follow up, 就是空间O(1)的做法:
这里卡在了如何update prevOne, prevTwo上,后来参考了别人的答案找到了方法,关键在于for循环里每次要更新curt = 0.
不过还是有一个地方不是很明白,最开始为什么s.charAt(0) != ‘0’的时候 prevTwo也等于1?
class Solution {
//follow up: O(1) space complexity
public int numDecodings(String s) {
if (s == null || s.length() == 0){
return 0;
}
int prevTwo = 0;
int prevOne = 0;
int curt = 0;
if (s.charAt(0) != '0'){
curt = 1;
prevOne = curt;
prevTwo = prevOne; //why this is 1 not 0?
}
for (int i = 1; i < s.length(); i++){
curt = 0;
int twoDigits = Integer.parseInt(s.substring(i - 1, i + 1));
if (twoDigits >= 10 && twoDigits <= 26){
curt += prevTwo;
}
int oneDigit = s.charAt(i) - '0';
if (oneDigit >= 1 && oneDigit <= 9){
curt += prevOne;
}
prevTwo = prevOne;
prevOne = curt;
}
return curt;
}
}