LeetCode in Java [12]*: 91. Decode Ways

本文探讨了一种将字母映射为数字的编码方式,并通过两个示例解释了如何计算字符串解码的可能性。提供了两种Java实现,一种使用动态规划,另一种更简洁的方法,展示了算法效率的提升。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

我写的动态规划比较麻烦,结果:

Success

Runtime: 1 ms, faster than 97.05% of Java online submissions for Decode Ways.

Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Decode Ways.

class Solution {
    public int numDecodings(String s) {
        if(s==null||s.length()==0){return 0;}
        if(s.charAt(0)=='0'){return 0;}
        if(s.length()==1){return 1;}
        int[] memo=new int[s.length()];
        memo[0]=1;
        int inst=(s.charAt(0)-'0')*10+s.charAt(1)-'0';
        if(inst>=10&&inst<=26&&inst!=10&&inst!=20){memo[1]=2;}
        else if((inst>0&&inst%10!=0)||inst==10||inst==20) memo[1]=1;
        int index=2;
        while(index<memo.length){
            int sec=s.charAt(index)-'0';
            int fst=s.charAt(index-1)-'0';
            fst=sec+fst*10;
            if(sec>0&&sec<=9){memo[index]+=memo[index-1];}
            if(fst<=26&&fst>=10){memo[index]+=memo[index-2];}
            index++;
        }
        return memo[s.length()-1];
    }

}

讨论里有个简洁一些的,放上来给大家参下:

public class Solution {
    public int numDecodings(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        int n = s.length();
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = s.charAt(0) != '0' ? 1 : 0;
        for(int i = 2; i <= n; i++) {
            int first = Integer.valueOf(s.substring(i-1, i));
            int second = Integer.valueOf(s.substring(i-2, i));
            if(first >= 1 && first <= 9) {
               dp[i] += dp[i-1];  
            }
            if(second >= 10 && second <= 26) {
                dp[i] += dp[i-2];
            }
        }
        return dp[n];
    }
}

这个会慢一点2ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值