【leetcode刷题笔记】Decode Ways

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

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

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.


 

题解:DP问题。

对于s中位置i(s[i] != '0')上的字符,有两种可能:

  1. 直接把i译码成对应的字母,那么此时有dp[i-1]中方法;
  2. 如果i和i-1上的字符可以共同组成一个字母(s(i-1,i)在[10,26]范围中),那么又有dp[i-2]种译码方法,所以此时dp[i] = dp[i-1]+dp[i-2];

代码如下:

复制代码
 1 public class Solution {
 2     private boolean isValidNum(String s,int i){
 3         if(i <= 0)
 4             return false;
 5         int first = s.charAt(i-1)-'0';
 6         int second = s.charAt(i)-'0';
 7         int num = first*10 + second;
 8         if(num >= 10 && num <= 26)
 9             return true;
10         return false;
11     }
12     public int numDecodings(String s) {
13         if(s==null || s.length() == 0)
14             return 0;
15         int length = s.length();
16         int[] dp = new int[length+1];
17         
18         dp[0] = 1;
19         dp[1] = s.charAt(0) == '0'?0:1;
20         
21         for(int i=2;i<=length;i++){
22             if(s.charAt(i-1) != '0')
23                 dp[i]=dp[i-1];
24             
25             if(isValidNum(s, i-1))
26                 dp[i] += dp[i-2];
27         }
28         return dp[length];        
29     }
30 }
复制代码
posted @   SunshineAtNoon  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示