Wednesday, April 10, 2013

Decode ways (C++ code)

LeetCode Decode Ways, Jun 25 '12
 难度3,出现频率4
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.
 思路:从末位倒着算,简单DP, 结果存在数组里。这道题没什么难点,但是要仔细,还要注意character和int的区别。


   int numDecodings(string s) {
       if(s.empty()) return 0;
       int n = s.length();
       int A[n];
       if(s[n-1] == '0') A[n-1] = 0; 

       else A[n-1] = 1;
    

      for(int i = n-2; i >= 0 ; i--){
        if(s[i] == '0') A[i] = 0;
        else if(s[i] == '1' || (s[i] == '2' && s[i+1] <= '6')) {
            if(i == n - 2);

               A[i] = A[i+1] + 1;
           else A[i] = A[i+1] + A[i+2];          
        }
        else   A[i] = A[i+1];

      }


      return A[0];

    }

No comments:

Post a Comment