zoukankan      html  css  js  c++  java
  • 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.

    Subscribe to see which companies asked this question

     
    一开始理解错了,以为11可以是3种,其实是两种。
    这题类似斐波那契数列
    f(n)=f(n-1)+f(n-2);
    不过这题是有条件的,要判断当所在位不为零,即是f(n-1),代表此次所得种类数不会增加,若为零,则不能这样拆,则这种情况不存在编码种类数。
     
     
     1 class Solution {
     2 public:
     3     int numDecodings(string s) {
     4     if(s.empty())
     5     return 0;
     6     if(s.size()==1)
     7     {
     8         if(s[0]=='0')
     9         return 0;
    10         else return 1;
    11     }
    12         int tmp1=0,tmp2=1;
    13         int len=s.size()-1;
    14         if(s[len]!='0')
    15         tmp1=1;
    16         for(int i=len-1;i>=0;i--)
    17         {
    18             int res=0;
    19            if(s[i]!='0')
    20            res+=tmp1;
    21            if(s[i]=='1'||(s[i]=='2'&&s[i+1]<='6'))
    22            res+=tmp2;
    23            tmp2=tmp1;
    24            tmp1=res;
    25         }
    26         return tmp1;
    27     }
    28 };
  • 相关阅读:
    struts2上传下载
    git教程
    mysql触发器2
    mysql触发器
    mysql set sql_mode 1055 报错
    一些乱七八糟的话
    linux 命令2
    linux命令 mysql
    东南亚之行(越南篇)
    flume常见配置
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5365786.html
Copyright © 2011-2022 走看看