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

    思路:

    思路很简单,就是要检查s.charAt(i)和s.char(i-1)是否能构成一个字母,如果不能res[i]=res[i-1],如果能res[i]=res[i-1]+res[i-2];

    但难处在于处理s.charAt(i)=='0'的各种情况,还有边界条件要处理好。

    本体代码:

    /**
     * Created by yuanxu on 17/4/13.
     */
    public class DP91 {
    
        public static int numDecodings(String s) {
            int len = s.length();
            if (len == 0) return 0;
            if (s.charAt(0) == '0')  return 0;
    
            // for both s.char(i) and res[i], make i begins with 1
            s = '0' + s;
            int res[] = new int[len+1];
    
            res[0] = 1; // for convince
            res[1] = 1;
    
            for (int i=2; i<=len; i++) {
                if (s.charAt(i) == '0') {
                    if (s.charAt(i-1) =='1' || s.charAt(i-1) =='2') {
                        res[i] = res[i-2];
                    } else {
                        return 0;
                    }
                } else {
                    res[i] = res[i-1];
                    if (s.charAt(i-1) == '1'|| (s.charAt(i-1)=='2' && s.charAt(i) < '7')) {
                        res[i] += res[i-2];
                    }
                }
            }
            return res[len];
        }
    
        /**
         *
         * @test
         */
        public  static void main(String[] args) {
    //        String s = "12312";
    //        String s = "0";
    //        String s = "01";
    //        String s = "10";
            String s = "110";
            System.out.println(numDecodings(s));
        }
    }
  • 相关阅读:
    php计算utf8字符串长度
    php和js字符串的acsii码函数
    快速排序的php实现
    bzoj 2822 [AHOI2012]树屋阶梯 卡特兰数
    bzoj 1485 [HNOI2009]有趣的数列 卡特兰数
    bzoj 4173 打表???
    bzoj [Noi2002]Savage 扩展欧几里得
    bzoj 3505 [Cqoi2014]数三角形 组合
    bzoj 2820 莫比乌斯反演
    Travel 并查集
  • 原文地址:https://www.cnblogs.com/pinganzi/p/6704730.html
Copyright © 2011-2022 走看看