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.

    Solution:

    Use Dynamic Programming method to solve the problem, for positition i, we can get that

    if substring(i-1,i) is a valid string, the number of ways decoding from the beginning to position i equals the number of ways decoding from the beginning to position i-1;

    if substring(i-2,i) is a valid string, the number of ways decoding from the beginning to position i equals the number of ways decoding from the beginning to position i-2;

     1 public class Solution {
     2     public int numDecodings(String s) {
     3         if(s==null||s.length()==0)
     4             return 0;
     5         int[] dp=new int[s.length()+1];
     6         dp[0]=1;
     7         if(isValid(s.substring(0,1))){
     8             dp[1]=1;
     9         }else{
    10             dp[1]=0;
    11         }
    12         for(int i=2;i<=s.length();++i){
    13             if(isValid(s.substring(i-1, i)))
    14                 dp[i]=dp[i-1];
    15             if(isValid(s.substring(i-2, i))){
    16                 dp[i]+=dp[i-2];
    17             }
    18             
    19         }
    20         return dp[s.length()];
    21     }
    22     private boolean isValid(String s) {
    23         // TODO Auto-generated method stub
    24         int N=s.length();
    25         if(N==1){
    26             return(s.charAt(0)>='1'&&s.charAt(0)<='9');
    27         }else if(N==2){
    28             return((s.charAt(0)=='1'&&s.charAt(1)>='0'&&s.charAt(1)<='9')||
    29                     (s.charAt(0)=='2'&&s.charAt(1)>='0'&&s.charAt(1)<='6'));
    30         }
    31         return false;
    32     }
    33 }
  • 相关阅读:
    2019 湖湘杯 Reverse WP
    2017第二届广东省强网杯线上赛--Nonstandard
    2019 上海市大学生网络安全大赛 RE部分WP
    2019 360杯 re wp--Here are some big nums
    MATLAB图像的代数运算
    编辑和剪绳子-头条2019笔试题
    奖品分配-头条2019笔试题
    TrajPreModel
    multiheadattention-torch
    腾讯笔试题-邻值查找
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4261399.html
Copyright © 2011-2022 走看看