leetcode 17: 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.


class Solution {
public:
    int numDecodings(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        // d[i] means from i to end, the number of ways to decode the substring.
        
        int size = s.size();
        
        if(size<=0)  return 0; 
        
        int d[size+1];
        d[size] = 1; // dummy number, for convinience issue in following loop.
        d[size-1] = s[size-1] == '0' ? 0 : 1; 
        
        for(int i=size-2; i>=0; i--) {
            if( s[i] == '0' ) {
                d[i] = 0;
            } else if( s[i] == '1' || (s[i]=='2' && s[i+1] <= '6'  ) ) {
                d[i] = d[i+1] + d[i+2];
            } else {
                d[i] = d[i+1];
            }
        }
        
        return d[0];
    }
};


posted @ 2013-01-08 04:17  西施豆腐渣  阅读(167)  评论(0编辑  收藏  举报