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.


    基本思想:

    本题利用动态规划记录前面的结果。难点是对0的处理。假设0前面是1或2以外的不论什么数字都无法解码。

    代码:

    public int numDecodings(String s) {  //java
            //deal with "0"
            if(s.startsWith("0"))
                return 0;
            
            int size = s.length();
            for(int i = 1; i< size; i++)
                if(s.charAt(i) == '0'&&(s.charAt(i-1)>'2'||s.charAt(i-1)=='0'))
                    return 0;
            
            if(size <=1)
                return size;
            
            int top = -1;
            int [] record = new int [size+1];
            record[0] = 0;
            record[1] = 1;
            if(Integer.valueOf(s.substring(0,2)) <=26&&
                    Integer.valueOf(s.substring(0,2))>=11&&
                    Integer.valueOf(s.substring(0,2))!=20)
                record[2] = 2;
            else record[2] = 1;
            
            for(int i = 3; i <=size; i++){
                if(Integer.valueOf(s.substring(i-2,i))==10 ||
                    Integer.valueOf(s.substring(i-2,i))==20)
                    record[i] = record[i-2];
                else if(Integer.valueOf(s.substring(i-2,i))<=26&&
                    Integer.valueOf(s.substring(i-2,i))>=11)
                    record[i] = record[i-2]+record[i-1];
                else record[i] = record[i-1];
            }
            return record[size];
        }


  • 相关阅读:
    bzoj 1093: [ZJOI2007]最大半连通子图
    bzoj 1266 1266: [AHOI2006]上学路线route
    poj 2104 K-th Number
    洛谷 P3313 [SDOI2014]旅行
    cogs 306. [SGOI] 糊涂的记者
    cogs 1164. 跑步
    洛谷 1821: [JSOI2010]Group 部落划分 Group
    洛谷 U3357 C2-走楼梯
    洛谷 P3014 [USACO11FEB]牛线Cow Line
    洛谷 P2982 [USACO10FEB]慢下来Slowing down
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6916664.html
Copyright © 2011-2022 走看看