Java solution with O(1) space and O(n) time


  • 0
    G
    public int numDecodings(String s) {
            int n= s.length();
            if(n==0) return 0;
            
            int a =1;
            int b = s.charAt(n-1)!='0'?1:0;
            
            int c =b;
            for(int i=n-2;i>=0;i--){
                if(s.charAt(i)=='0'){
                    c=0;
                    a = b;
                    b = c;
                    continue;
                }
                else{
                    c= Integer.parseInt(s.substring(i,i+2))<=26?b+a:b;
                    a = b;
                    b =c;
                }
            }
            return c;
        }
    

Log in to reply
 

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