Java , tail recursion, 1-2ms


  • 0
    T
     public class Solution {
      public int numDecodings(String s) {
         if(s==null||s.length()==0){
            return 0;
          }
         int m=s.charAt(0) != '0' ? 1 : 0;
         if(s.length()==1){
             return m;
         }
        return numDecodings1( s ,2,1,m);
      }
    public int numDecodings1(String s ,int i,int num1,int num2) {
           if(i > s.length()){
               return num2;
           }
            char singleChar = s.charAt(i-1);
            char tenChar =  s.charAt(i-2);
            int singleDigit=singleChar-'0';
            int sumDigit=(tenChar-'0')*10+singleDigit;
            
            if(sumDigit >= 11 && sumDigit <= 26&&singleDigit !=0) {
                return numDecodings1( s ,++i,num2,num1+num2);
            }else if(sumDigit==10||sumDigit==20) {
               return numDecodings1( s , ++i,num2,num1);
            }  else if(singleDigit!=0) {
               return numDecodings1( s , ++i,num2,num2);
            } 
           return 0;
      }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.