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));
        }
    }
  • 相关阅读:
    ojdbc15-10.2.0.4.0.jar maven 引用报错 Dependency 'com.oracle:ojdbc15:10.2.0.4.0' not found
    两个js文件之间函数互调问题
    Win10连接远程桌面时提示“您的凭据不工作”
    Examples_08_03
    ant打包命令
    SVN版本日志对话框命令使用指南
    activiti_SpringEnvironment
    shell脚本
    python爬虫
    php正则表达式总结
  • 原文地址:https://www.cnblogs.com/pinganzi/p/6704730.html
Copyright © 2011-2022 走看看