91 Decode Ways

原文地址:https://blog.csdn.net/worldwindjp/article/details/19938131

主要问题:

特殊数字100、101、0的判断上

因为原文要求数字为1-26,所以01,00,这些不符合要求,但是从数值(int)上符合要求



正文

 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.
http://oj.leetcode.com/problems/decode-ways/

题意解析:给你一串数字,解码成英文字母。
类似爬楼梯问题,但要加很多限制条件。
定义数组number,number[i]意味着:字符串s[0..i-1]可以有number[i]种解码方法。
回想爬楼梯问题一样,number[i] = number[i-1] + number[i-2]
但不同的是本题有多种限制:
第一: s[i-1]不能是0,如果s[i-1]是0的话,number[i]就只能等于number[i-2]
第二,s[i-2,i-1]中的第一个字符不能是0,而且Integer.parseInt(s.substring(i-2,i))获得的整数必须在0到26之间。

1010,生成的number数组为:[1,1,1,1,1]
10000,生成的number数组为:[1,1,1,0,0,0,0,0,0]
AC代码:

[java]  view plain  copy
  1. public class Solution {  
  2.     public int numDecodings(String s) {  
  3.         if(s==null || s.length()==0) {  
  4.             return 0;  
  5.         }  
  6.         if(s.charAt(0)=='0') {  
  7.             return 0;  
  8.         }  
  9.           
  10.         int [] number = new int[s.length() + 1];  
  11.         number[0] = 1;  
  12.         number[1] = 1;  
  13.         int tmp;  
  14.         for(int i=2;i<=s.length();i++) {  
  15.             //检查当前字符是不是'0'  
  16.             tmp = Integer.parseInt(s.substring(i-1,i));  
  17.             if(tmp!=0) {              
  18.                 number[i] = number[i-1];  
  19.             }  
  20.             //检查当前字符和前一个字符组合在一起是否在1-26之间  
  21.             if(s.charAt(i-2)!='0') {  
  22.                 tmp = Integer.parseInt(s.substring(i-2,i));  
  23.                 if(tmp>0&&tmp<=26) {  
  24.                     number[i] += number[i-2];  
  25.                 }  
  26.             }  
  27.         }  
  28.         return number[s.length()];  
  29.     }  
  30. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值