难度:中等。
动态规划来做。first和second分别表示以s[i-2]和s[i-1]字符为结尾的字符串的组合数。
正确解法:
class Solution {
public:
int translateNum(int num) {
string str = to_string(num);
int n = str.length();
if(n == 0)return 0;
int first = 1, second = 1;
for(int i = 1; i < n; i++){
if(str[i - 1] == '1' || (str[i - 1] == '2' && str[i] <= '5')){
swap(first, second);
second += first;
}
else{
first = second;
}
}
return second;
}
};
结果: