zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    微信小程序右上角胶囊的位置
    NLP复习大纲
    网站收藏
    css中如何调整插入背景图片的大小
    禁止Power Apps Canvas用户通过SharePoint Online UI界面访问站点list
    c++ vector基本知识
    c++ map基本知识
    c++ string操作
    python学习笔记30:操作excel
    c++, 如何run一个c++程序
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3865991.html
Copyright © 2011-2022 走看看