动态规划
将数值变为字符串,依次遍历,每次遍历字符时,观察其前面一个字符的值
例如:
xxxx12xxxx 当遍历到2时,dp(xxxx)和dp(xxxx1)的结果已知,则dp(xxxx12) = dp(xxxx) + dp(xxxx1),因为其可以有两种表达形式xxxx1 2和xxxx 12
xxxx27xxxx 当遍历到7时,dp(xxxx)和dp(xxxx1)的结果已知,则dp(xxxx27) = dp(xxxx1),因为其表示形式只能是xxxx2 7,不存在xxxx 27
class Solution {
public int translateNum(int num) {
String str = String.valueOf(num);
if(str.length() < 2) return str.length();
int number_1 = 1;
int number_2 = 1;
if(compare(str.charAt(0), str.charAt(1)))
number_2 ++;
for(int i = 2; i < str.length(); i++){
if(compare(str.charAt(i - 1), str.charAt(i))){
number_2 = number_1 + number_2;
number_1 = number_2 - number_1;
}else{
number_1 = number_2;
}
}
return number_2;
}
private boolean compare(char ch1, char ch2){
if(ch1 == '1') return true;
if(ch1 == '2' && (ch2 >= '0' && ch2 <= '5')) return true;
return false;
}
}