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.

    Analysis:

    This is a DP problem. d[i] is the number of ways to decode the first i chars.

    d[i]=d[i-2]+d[i-1] if num(i-1,i) is a valid number and num(i,i) is a valid number.

    NOTE: for a string with 2 chars, the number should be between 10 and 26. For a string with 1 char, the valid number should between 1 and 9. "0","01","02"...like this are all invalid.

    Solution:

     1 public class Solution {
     2     public int numDecodings(String s) {
     3         if (s.length()==0) return 0;
     4         int[] d = new int[s.length()+1];
     5         d[0]=1;
     6         for (int i=1;i<d.length;i++){
     7             d[i]=0;
     8             int start = 0;
     9             if (i-2>start) start = i-2;
    10             for (int k=start;k<i;k++){
    11                String temp = s.substring(k,i);
    12                if (temp.length()==1&&!temp.equals("0"))
    13                    d[i]+=d[k];
    14                if (temp.length()==2){
    15                    int num = Integer.parseInt(temp);
    16                    if (num<=26 && num>=10)
    17                        d[i]+=d[k];
    18                }
    19             }
    20          }
    21          return d[s.length()];      
    22     }
    23 }
  • 相关阅读:
    Python long() 函数
    Python frozenset() 函数
    java对象和构造方法的区别
    回顾方法和方法调用及加深
    面向过程&面向对象
    稀疏数组
    冒泡排序与八大排序
    Arrays类与常用功能
    二维数组的理解代码
    数组的使用
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4098786.html
Copyright © 2011-2022 走看看