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.

    [解题思路]

    [Thoughts]
    Similar as "[LeetCode] Climbing Stairs, Solution". DP. Just add some logic to compare character.


    Transformation function as:
    Count[i] = Count[i-1]  if S[i-1] is a valid char
           or   = Count[i-1]+ Count[i-2]  if S[i-1] and S[i-2] together is still a valid char

    f1 表示 fn-1; f2 表示 fn-2;

     1 public class Solution {
     2     public int numDecodings(String s) {
     3         if(s == null || s.length() == 0) return 0;
     4         int len = s.length();
     5         if(len==1) return check1(s.charAt(0));
     6         if(len>=1 && s.charAt(0)=='0') return 0;
     7         int f2= 1,f1=0,fn=0;
     8         f1 = check1(s.charAt(0))*check1(s.charAt(1))+ check2(s.charAt(0),s.charAt(1));
     9         for(int i=2;i<len;i++){
    10             if(check1(s.charAt(i))==1) 
    11                 fn += f1;
    12             if(check2(s.charAt(i-1),s.charAt(i))==1)
    13                 fn += f2;
    14             if(fn == 0) 
    15                 return 0;
    16             f2 = f1;
    17             f1 = fn;
    18             fn = 0;
    19                 
    20         }
    21         return f1;
    22     }
    23     public int check1 (char a){
    24         return (a>='1' && a<= '9')?1:0;
    25     }
    26     public int check2 (char a,char b){
    27         if(a=='1'||(a=='2'&& (b>='0'&&b<='6'))) return 1;
    28         else return 0;
    29     }
    30 }
  • 相关阅读:
    操作元素
    CSS3 制作网格动画效果
    网页边栏过渡动画
    超炫的 CSS3 页面切换动画效果
    多种鼠标悬停效果
    各种 SVG 制作单选和多选框动画
    全屏遮罩层效果(10种)
    FancyBox – 经典 Lightbox 效果插件
    CSS3 & SVG 制作钟表
    20种新颖的按钮风格和效果【附源码】
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3537895.html
Copyright © 2011-2022 走看看