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.
Example
Given encoded message 12
, it could be decoded as AB
(1 2) or L
(12).
The number of ways decoding 12
is 2.
第一种笨办法,递归:
public class Solution { public int numDecodings(String str) { if (str.length() == 0 || str.charAt(0) == '0') return 0; if (str.length() == 1) return 1; String subStr = str.substring(0, 2); // 0,1 int val = Integer.parseInt(subStr); if (str.length() == 2) { if (val <= 26) { return 1 + (str.charAt(1) == '0' ? 0 : 1) ; } else { return (str.charAt(1) == '0' ? 0 : 1); } } if (val <= 26) { return numDecodings(str.substring(1)) + numDecodings(str.substring(2)); } else { return numDecodings(str.substring(1)); } } }
第二种,DP。
用total[i]表示从i 到 string.length() - 1总共的解法。 我们可以从最后一个数字开始,最后一个数字如果在1-9之间,只有一种decode way, total[length - 1] = 1. 对于倒数第二个数字呢,如果倒数第二个数字不是0,很明显,我们至少有total[i] = total[i + 1], 如果俩个数字合在一起可以组成一个valid number, 那么total[i] += total[i + 2].
1 public class Solution { 2 /** 3 * @param s a string, encoded message 4 * @return an integer, the number of ways decoding 5 */ 6 public int numDecodings(String s) { 7 if (s == null || s.length() < 1) return 0; 8 int[] total = new int[s.length()]; 9 10 for (int i = s.length() - 1; i >= 0; i--) { 11 char c = s.charAt(i); 12 if (c >= '1' && c <= '9') { 13 if(i == s.length() - 1) { 14 total[i] = 1; 15 } else { 16 total[i] = total[i + 1]; 17 String strNumber = s.substring(i, i + 2); 18 int number = Integer.parseInt(strNumber); 19 if (number <= 26) { 20 if (i + 2 == total.length) { 21 total[i] += 1; 22 } else { 23 total[i] += total[i + 2]; 24 } 25 } 26 } 27 } 28 } 29 return total[0]; 30 } 31 }