zoukankan      html  css  js  c++  java
  • [LeetCode] Decode Ways(DP)

    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.

    就是要注意0的出现

    class Solution {
    public:
        int numDecodings(string s) {
            int len = s.size();
            if(len==0)
                return 0;
            vector<int> num(len,0);//第i个位置记录从s的第0个位置开始到第i个位置共有几种解码方式
            if(len>=1 && s[0]=='0')
                     return 0;
            
            num[0] = 1;
            if(len==1)
                return num[0];
                
            string s0 = s.substr(0,2);
            int d  = sToInt(s0);
            int n=0;
            if(d>10 && d<=26 &&  d!=20)
                num[1] = 2;
            else if((s[1] =='0' && (s[0]=='1'|| s[0]=='2'))||s[1]!='0')
                num[1] = num[0];
            else
                return 0;
            
            
            for(int i=2;i<len;i++){
                if(s[i-1]=='0'){
                    if(s[i]!='0'){
                        num[i] = num[i-1];
                        continue;
                    }
                    else
                        return 0;
                }
            
                s0 = s.substr(i-1,2);
                d  = sToInt(s0);
                if(s[i]=='0'){
                    if(d==10 || d==20){
                       num[i] = num[i-2];
                       continue;
                    }
                       
                   else 
                       return 0;
                }
                
                if(d>10 && d<=26 )
                    num[i] = num[i-1]+num[i-2];
                else
                    num[i] = num[i-1];
            
            
            }//end for
            return num[len-1];
        }
    private:
        int sToInt(string s){
          istringstream is(s);
          int d;
          is>>d;
          return d;
        
        }
    };
  • 相关阅读:
    线程同步的几种实现方案
    关于java中三种初始化块的执行顺序
    java数组
    Codeblocks 17汉化
    聚焦天狗
    linux下搭建svn添加多个仓库(项目)
    使用Python在windows环境下获取Linux服务器的磁盘、内存等信息
    python smtplib使用163发送邮件 报错 554 DT:SPM
    防抖与节流
    js
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3909556.html
Copyright © 2011-2022 走看看