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.
本题和爬楼梯的题目非常类似。使用一个数组做DP 即可。
但不同的是本题有多种限制:
第一: s[i-1]不能是0,如果s[i-1]是0的话,num[i]就只能等于num[i-2]
第二,s[i-2,i-1]中的第一个字符不能是0,而且Integer.parseInt(s.substring(i-2,i))获得的整数必须在0到27之间
1 public class Solution { 2 public int numDecodings(String s) { 3 if(s == null || s.length() == 0) return 0; 4 int[] num = new int[s.length()+1]; 5 num[0] = 1; 6 num[1] = s.charAt(0) != '0' ? 1:0; 7 for(int i = 2; i <= s.length(); i++){ 8 if(s.charAt(i-1) != '0') 9 num[i] = num[i-1]; 10 if(s.charAt(i-2) != '0' && Integer.parseInt(s.substring(i-2,i)) < 27) 11 num[i] += num[i-2]; 12 } 13 return num[s.length()]; 14 } 15 }