当前位置:网站首页>Sword finger offer 46. translate numbers into strings

Sword finger offer 46. translate numbers into strings

2022-07-23 14:32:00 ATTACH_ Fine

subject

Given a number , We translate it as a string according to the following rules :0 Translate into “a” ,1 Translate into “b”,……,11 Translate into “l”,……,25 Translate into “z”. A number may have more than one translation . Please program a function , Used to calculate how many different translation methods a number has .

Example :
 Insert picture description here

Ideas

 Insert picture description here

Code

class Solution {
    
    public int translateNum(int num) {
    
        //  Set up a dynamic programming list  dp[i]  Representative to  x_i Number of translation schemes for ending numbers .
        String str = String.valueOf(num);
        int len = str.length();
        int[] dp = new int[len+1];
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i <= len; i++){
    
            String temp = str.substring(i-2,i);
            if(temp.compareTo("10") >= 0 && temp.compareTo("25") <= 0){
    
                dp[i] = dp[i-1] + dp [i-2];
            }else
                dp[i] = dp[i-1];
        }
        return dp[len];       
    }
}
原网站

版权声明
本文为[ATTACH_ Fine]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230803200026.html