1. 程式人生 > 其它 >名企中等——把數字翻譯成字串

名企中等——把數字翻譯成字串

技術標籤:面試演算法題筆試演算法題

題目描述
有一種將字母編碼成數字的方式:‘a’->1, ‘b->2’, … , ‘z->26’。

現在給一串數字,返回有多少種可能的譯碼結果

輸入
“12”
返回值
2
說明
2種可能的譯碼結果(”ab” 或”l”)

示例2
輸入
“31717126241541717”
返回值
192


import java.util.*;


public class Solution {
    /**
     * 解碼
     * @param nums string字串 數字串
     * @return int整型
     */
    public int solve (String nums){
        // write code here
        // 要考慮0的場景

        if(null == nums || nums.charAt(0) == '0'){
            return 0;
        }
        if(nums.length() == 1){
            return 1;
        }

        int[] DP = new int[nums.length()+1];

        DP[0] = 1;
        DP[1] = 1;
        for(int i = 2; i<=nums.length(); i++){
            if(nums.charAt(i-1) == '0'){
                if(nums.charAt(i-2) == '0' || nums.charAt(i-2) >= '3'){
                    return 0;
                } else{
                    DP[i] = DP[i-2];
                }
            } else{
                if(nums.charAt(i-2) != '0' && nums.substring(i-2,i).compareTo("26") <= 0){
                    DP[i] = DP[i-2]+DP[i-1];
                } else {
                    DP[i] = DP[i-1];
                }
            }
        }

        return DP[nums.length()];
    }
}