Created
January 4, 2013 14:34
-
-
Save pdu/4452971 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int numDecodings(string s) { | |
| if (s.empty()) | |
| return 0; | |
| int n = s.length(); | |
| int f[3] = {1, 1, 1}; | |
| for (int i = 0; i < n; ++i) { | |
| f[i % 3] = 0; | |
| if (s[i] > '0') | |
| f[i % 3] += f[(i + 2) % 3]; | |
| if (i != 0 && s[i - 1] > '0' && (s[i - 1] - '0') * 10 + s[i] - '0' <= 26) | |
| f[i % 3] += f[(i + 1) % 3]; | |
| } | |
| return f[(n + 2) % 3]; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment