Leetcode–Decode Ways

The Problem:

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.

Notes:

  1. A DP problem. An important observation is that for multi-way sequences  such as  ‘1”2’, the regression function is ways[i] = ways[i-1] + ways[i-2]
  2. Watch out for details:
    1. ‘0’ can only pair with previous ‘1’ or ‘2’, which means ways[i] = ways[i-2]
    2. when using ways[i-2] need to check the bounds

Java Solution

public class Solution {
    public int numDecodings(String s) {
        int n = s.length();
        if(n==0)return 0;
        int[] ways = new int[n];
        if(s.charAt(0)=='0')
            return 0;
        else
            ways[0] = 1;
            
        for(int i = 1; i < n; i++){
            if(s.charAt(i)=='0'){ // only valid if previous is 1 or 2
                if(s.charAt(i-1)=='2'||s.charAt(i-1)=='1'){
                    ways[i] = i>=2 ? ways[i-2]:1;
                }
                else
                    return 0;
            }
            else{
                if(isValid(s.charAt(i-1), s.charAt(i))){
                    // have multiple ways
                    ways[i] = i>=2 ? ways[i-1]+ways[i-2] : 2;
                }
                else{
                    ways[i] =ways[i-1];
                }
            }
        }
        return ways[n-1];
    }
    
    private boolean isValid(char a, char b){
        if(a=='1')
            return true;
        if(a=='2' && b <= '6')
            return true;
        return false;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s