当前位置:网站首页>[※ leetcode refers to offer 46. Translate numbers into strings (medium)]

[※ leetcode refers to offer 46. Translate numbers into strings (medium)]

2022-04-23 21:21:00 Minaldo7

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 1:

Input : 12258
Output : 5
explain : 12258 Yes 5 Different translations , Namely "bccfi", “bwfi”, “bczi”, “mcfi" and "mzi”

Tips :

0 <= num < 231

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

Dynamic programming
from LeetCode: Zhu once

class Solution {
    
    /*  Dynamic programming   Similar to the problem of jumping steps, but with additional restrictions   give an example : Given number  122  There are three possibilities of translation   The first one is bcc 122  The second kind  bw 1 22  The third kind of  mc 12 2  It can be observed that when traversing from left to right , There is a case of selecting one character or two characters   Like jumping one or two spaces   But the title gives limitations   When you want to jump two spaces   The selected two digits meet  >=10 And <=25 , When 0 As the leading digit of ten digits , Not an option   If the appeal conditions are not met   There is no jumping two spaces   You can only jump one space to reach the target   So when num[i-1,i]  Spliced tens  >=10 And <=25  when   Yes  dp[i] = dp[i-1] + dp[i-2]  That is, you can jump two spaces and one space   When num[i-1,i]  Spliced tens  >25 perhaps <10  when  dp[i] = dp[i-1]  That is, you can only choose a scheme that jumps one grid  */  
    public int translateNum(int num) {
    
        String str = String.valueOf(num);
        int[] dp = new int[str.length()+1];
        dp[0] = dp[1] = 1;
        for(int i=2;i<=str.length();i++){
    
            String temp = str.substring(i-2,i);
            if(temp.compareTo("10")>=0 && temp.compareTo("25")<=0){
    
                dp[i] = dp[i-2] + dp[i-1];
            }else{
    
                dp[i] = dp[i-1];
            }
        }
        return dp[str.length()];
    }
}

Execution results :

 Insert picture description here

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