Java 5ms Accepted Solution (easy but lengthy)


  • 0
    G
    public class Solution {
        public int numDecodings(String s) {
            int l = s.length();
            if (l == 0){
                return 0;
            }
            char[] chars = s.toCharArray();
            if (chars[0] == '0'){
                return 0;
            }
            int[] ways = new int[l];
            ways[0] = 1;// all can be represented in at least 1 way as single chars
            int doubledigit;
            for(int i=1;i<l;i++){
                doubledigit = Integer.parseInt("" + chars[i-1]+chars[i]);
                if (doubledigit == 0){
                    return 0;//invalid input
                }
                if( doubledigit <= 26 && doubledigit >=10){
                    if (i==1){//special handling of first two chars
                        if (doubledigit == 10 || doubledigit == 20){
                            ways[i] = ways[i-1]; 
                        } else {
                            ways[i] = ways[i-1] + 1;
                        }
                    } else {
                        if (doubledigit == 10 || doubledigit == 20){
                            ways[i] = ways[i-2]; 
                        } else{
                            ways[i] = ways[i-1] + ways[i-2]; 
                        }
                    }
                } 
                else {
                    if (doubledigit % 10 == 0){
                        return 0;//invalid e.g. 60 in 12015160102
                    } else {
                        ways[i] = ways[i-1];
                    }
                }
            }
            return ways[l-1];
        }
    }

Log in to reply
 

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