Decode ways

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. Given encoded message 12, it could be decoded as AB (1 2) or L (12). The number of ways decoding 12 is 2.

Key Points:

  1. Conner cases!
    public int numDecodings(String s) {
        //f(i) = f(i+1)/f(i+1) + f(i+2)
        int len = s.length();
        if(len==0){return 0;}

        int last = s.charAt(len-1)=='0'?0:1, 
            oneBeforeLast =1;

        for(int i= s.length()-2; i>=0; i--){
            int t = last , curr=Integer.parseInt(s.substring(i,i+2));
            if(curr ==0){
                return 0;
            }
            else if(curr>26){
                last = last;
            }else if(curr>=10&&curr<=26){
                last = last + oneBeforeLast;
            }else if(curr>0&&curr<10){
                last = 0;
            }

            oneBeforeLast = t;

        }

        return last;
    }

results matching ""

    No results matching ""