leetcode--Decode Ways

来源:互联网 发布:iphone6s数据漫游 编辑:程序博客网 时间:2024/05/20 23:32

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.

[java] view plain copy
  1. public class Solution {  
  2.     public int numDecodings(String s) {  
  3.     int len = s.length();  
  4.         if(len == 0return 0;  
  5.         int[] flag = new int[len+1];  
  6.         flag[len] = 1;  
  7.         if(s.charAt(len-1)!='0'){  
  8.             flag[len-1] = 1;  
  9.         }else{  
  10.             flag[len-1] = 0;  
  11.         }         
  12.         for(int i=len-2;i>=0;i--){  
  13.             if(s.charAt(i)=='0') flag[i]=0;  
  14.                 else{  
  15.                 if(s.charAt(i)>'2'||(s.charAt(i)=='2'&&s.charAt(i+1)>'6')){  
  16.                     flag[i] = flag[i+1];  
  17.                 }else{  
  18.                     flag[i] = flag[i+1]+flag[i+2];  
  19.                 }  
  20.             }  
  21.         }  
  22.         return flag[0];  
  23.     }  
  24. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46442729

原创粉丝点击