Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 4, 2013 14:34
Show Gist options
  • Select an option

  • Save pdu/4452971 to your computer and use it in GitHub Desktop.

Select an option

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
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