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

    Solution: the most important one is matrix[0] = 1. 

     1 public class Solution {
     2     public int numDecodings(String s) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(s == null || s.length() == 0) return 0;
     6         else{
     7             int[] matrix = new int[s.length()+1];
     8             matrix[0] = 1;
     9             matrix[1] = 1;
    10             if(Integer.valueOf(s.substring(s.length() -1, s.length())) == 0)
    11                 matrix[1] = 0;
    12             for(int i = s.length() - 2; i > -1; i --){
    13                 int sum = 0;
    14                 if(Integer.valueOf(s.substring(i, i+1)) > 0){
    15                     sum += matrix[s.length() - i - 1];
    16                 }
    17                 if(Integer.valueOf(s.substring(i, i+2)) < 27 && Integer.valueOf(s.substring(i, i+2)) > 9)
    18                     sum += matrix[s.length() - i - 2];
    19                 matrix[s.length() - i] = sum;
    20             }
    21             return matrix[s.length()];
    22         }
    23     }
    24 }

     第二遍:

    从前往后做,这样更简单。

     1 public class Solution {
     2     public int numDecodings(String s) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(s == null || s.length() == 0) return 0;
     6         int[] matrix = new int[s.length() + 1];
     7         matrix[0] = 1;
     8         for (int i = 0; i < s.length(); i ++){
     9             if (0 < Integer.valueOf(s.substring(i, i + 1)))
    10                 matrix[i + 1] += matrix[i];
    11             if (i > 0 && Integer.valueOf(s.substring(i - 1, i + 1)) < 27 && Integer.valueOf(s.substring(i - 1, i + 1)) > 9)
    12                 matrix[i + 1] += matrix[i - 1];
    13         }
    14         return matrix[s.length()];
    15     }
    16 }
  • 相关阅读:
    织梦dedecms网站数据库出错如何修复
    如何实现织梦dedecms会员登陆后就不显示广告
    搜索框里显示字段鼠标点击后就隐藏的方法
    织梦dedecms首页如何调用联动类别代码
    织梦CMS友情链接调用方法技巧大全
    DedeCMS 标题seo优化给列表页加上第x页
    DedeCMS采集教程:过滤替换的技巧
    织梦dedecms网站数据库出错如何修复
    压力测试-查看索引
    时间同步服务部署
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3340018.html
Copyright © 2011-2022 走看看