LeetCode—Sword refers to Offer: Translate numbers into strings (dynamic programming)

Translate numbers into strings (medium)

September 6, 2020

Question source: Likou

Insert picture description here
Problem solving

State quantity: record the current maximum number of translations.
State transition equation: When the combination of the last two numbers is in the range of [10,25], it means that it can be regarded as a whole number, then the number of numbers will be one less than the previous number. The last maximum translation number is dp[i-2]; if it is not in this range, it means that it cannot be regarded as a whole number, and the result is consistent with the last maximum translation number.

class Solution {
    
    
    public int translateNum(int num) {
    
    
        String str_num=String.valueOf(num);
        int[] dp=new int[str_num.length()+1];
        //初始化
        dp[0]=1;
        dp[1]=1;
        for(int i=2;i<=str_num.length();i++){
    
    
            //切割前两位字符数字
            String tmp_str=str_num.substring(i-2,i);
            //比较
            dp[i]=(tmp_str.compareTo("10")>=0 && tmp_str.compareTo("25")<=0)?dp[i-1]+dp[i-2]:dp[i-1];
        }
        return dp[str_num.length()];
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41541562/article/details/108427583