Saturday, January 10, 2015

LeetCode 91: 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.
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.
public class Solution {
    public int numDecodings(String s) {
        // DP problem
        // Backtracking solution exceeded time limit.
        // This question is similar to "Climbing Stairs" but need more constrained conditions.
        int n = s.length();
        
        if (n==0 || s.charAt(0)=='0')
            return 0;
            
        int[] deWays = new int[n+1];
        
        deWays[0] = 1; // Note: Here we should define it as 1 rather than 0 for future calculation.
        deWays[1] = 1;
        
        for (int i = 2; i <= n; i++)
        {
            deWays[i] = 0;
            
            if (place(s.substring(i-1,i)))
                deWays[i] += deWays[i-1];
            
            if (place(s.substring(i-2, i)))
                deWays[i] += deWays[i-2];
        }
        
        return deWays[n];
    }
    
    private boolean place(String str)
    {
        if (str.charAt(0)=='0')
            return false;
            
        int num = Integer.parseInt(str);
        
        if (num>=1 && num<=26)
            return true;
        else
            return false;
    }
}

No comments:

Post a Comment