Friday, January 9, 2015

Decode Ways (LeetCode String)

Question: 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.

Idea: Dynamic programming. We use dp[i] to denote the number of ways to decode the message before i (exclusive i). Then from i-1 and i-2, there are several possible scenarios:
1) from dp[i-1]: the digit must be among 1->9.
2) from dp[i-2]: the digit must be among 10->26.
So dp[i]= (letter[i] among 1->9)?dp[i-1]:0 + (letter[i] among 10->26)?dp[i-2]:0

Time: O(n) Space: O(n) (can be reduced to O(1) by reusing dp[i-2], dp[i-1], dp[i])

Easier to Understand Code:
 public class Solution {  
   public int numDecodings(String s) {  
     if(s.length()==0||(s.charAt(0)=='0'))  
       return 0;  
     int[] dp=new int[s.length()+1];  
     dp[0]=1;  
     dp[1]=(s.charAt(0)=='0')?0:1;  
     for(int i=2;i<=s.length();i++)  
     {  
       int lastTwoDigits=Integer.parseInt(s.substring(i-2,i));  
       dp[i]=((s.charAt(i-1)!='0')?dp[i-1]:0)+((lastTwoDigits>=10&&lastTwoDigits<=26)?dp[i-2]:0);  
     }  
     return dp[s.length()];  
   }  
 }  

Cleaner Code: 
 public class Solution {  
   public int numDecodings(String s) {  
     if(s.length()==0)  
       return 0;  
     int[] num=new int[s.length()+1];  
     num[0]=1;  
     num[1]=(s.charAt(0)=='0')?0:1;  
     for(int i=2;i<=s.length();i++)  
     {  
       if(s.charAt(i-1)!='0')  
         num[i]=num[i-1];  
       int lastTwoDigits=Integer.parseInt(s.substring(i-2,i));  
       if(lastTwoDigits>=10&&lastTwoDigits<=26)  
         num[i]+=num[i-2];  
     }  
     return num[s.length()];  
   }  
 }  

No comments:

Post a Comment