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));
        }
    }
  • 相关阅读:
    mybatis源码追踪2——将结果集映射为map
    Mybatis的cache
    mybatis拦截器
    mybatis中单个参数的引用
    mybatis源码追踪1——Mapper方法用法解析
    win8 下 intellij idea 13 中文输入覆盖的问题
    firebug中html显示为灰色的原因总结
    extjs4.0以上添加多行工具栏的方法
    去除eclipse的validating
    An interview question from MicroStrategy
  • 原文地址:https://www.cnblogs.com/pinganzi/p/6704730.html
Copyright © 2011-2022 走看看