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.
public class Solution { public int numDecodings(String s) { // Start typing your Java solution below // DO NOT write main() function ArrayList<Integer> solutions = new ArrayList<Integer>(); if(s.length()!= 0){ recursion(s,solutions); } return solutions.size(); } public void recursion(String s,ArrayList<Integer> solutions ){ if(s.length() == 0){ solutions.add(1); } else{ int value = Character.getNumericValue(s.charAt(0)); if(value >0 && value <=9){ recursion(s.substring(1),solutions); } if(s.length() >=2){ int value1 = Character.getNumericValue(s.charAt(0)); int value2 = Character.getNumericValue(s.charAt(1)); if(value1 == 1 && value2 >=0 && value2 <=9){//value1 is 1 recursion(s.substring(2),solutions); } if(value1 == 2 && value2 >=0 && value2 <=6){//value1 is 2 two conditions recursion(s.substring(2),solutions); } } } } }
mistake: Character.getNumericValue(s.charAt(0)); character to get int from string
public class Solution { public int numDecodings(String s) { if(s.length() == 0) return 0; int[] num = new int[2]; num[0] = 1; // decode the first two integers num[1] = 1; // decode the first integer for(int i = 0 ; i < s.length();i++){ int temp = 0; if(s.charAt(i) != '0') temp += num[1]; if(i>0){ int a = Integer.parseInt(s.substring(i-1,i+1)); if(s.charAt(i-1) !='0' && a>=1 && a<=26){ temp+= num[0]; } } num[0] = num[1]; num[1] = temp; } return num[1]; } }
learned: return num[1] , like clim stairs temp is total decode ways for s.substring(0,2)