dynamic programming
1 public class Solution { 2 public int numDecodings(String s) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int length = s.length(); 6 if(0 == length || s.charAt(0) == '0') 7 return 0; 8 int[] dp = new int[length+1]; 9 dp[0] = 1; 10 dp[1] = 1; 11 for(int i = 2; i < length+1; i++) 12 { 13 char curChar = s.charAt(i - 1); 14 int curNum = curChar - '0'; 15 // s[i] is not valid 16 if (curNum == 0) { 17 String twoNum = s.substring(i - 2, i); 18 // s[i-1][i] is valid 19 if (Integer.parseInt(twoNum) <= 26 20 && Integer.parseInt(twoNum) >= 10) { 21 dp[i] = dp[i - 2]; 22 } else { 23 dp[i] = 0; 24 } 25 } 26 // s[i] is valid 27 else { 28 String twoNum = s.substring(i - 2, i); 29 // s[i-1][i] is valid 30 if (Integer.parseInt(twoNum) <= 26 31 && Integer.parseInt(twoNum) >= 10) { 32 dp[i] = dp[i - 1] + dp[i - 2]; 33 } else { 34 dp[i] = dp[i - 1]; 35 } 36 } 37 } 38 return dp[length]; 39 } 40 }