Decode ways
Count the ways to decode a digit string into letters, where A is 1 and Z is 26.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
ways(i) counts the decodings of the first i digits. The last letter is either the single digit 1-9 (add ways(i-1)) or the last two digits forming 10-26 (add ways(i-2)). Both can apply at once, so the counts add. Only the last two counts are read, so two variables are enough.
Code
public static int NumDecodings(string s) {
int prev2 = 1;
int prev1 = s[0] != '0' ? 1 : 0;
for (int i = 2; i <= s.Length; i++) {
int cur = 0;
if (s[i - 1] != '0') cur += prev1;
int two = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (two >= 10 && two <= 26) cur += prev2;
prev2 = prev1; prev1 = cur;
}
return prev1;
}static int numDecodings(String s) {
int prev2 = 1;
int prev1 = s.charAt(0) != '0' ? 1 : 0;
for (int i = 2; i <= s.length(); i++) {
int cur = 0;
if (s.charAt(i - 1) != '0') cur += prev1;
int two = (s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0');
if (two >= 10 && two <= 26) cur += prev2;
prev2 = prev1; prev1 = cur;
}
return prev1;
}int numDecodings(const string& s) {
int prev2 = 1;
int prev1 = s[0] != '0' ? 1 : 0;
for (int i = 2; i <= (int)s.size(); i++) {
int cur = 0;
if (s[i - 1] != '0') cur += prev1;
int two = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (two >= 10 && two <= 26) cur += prev2;
prev2 = prev1; prev1 = cur;
}
return prev1;
}def num_decodings(s: str) -> int:
prev2 = 1
prev1 = 1 if s[0] != '0' else 0
for i in range(2, len(s) + 1):
cur = 0
if s[i - 1] != '0': cur += prev1
two = int(s[i - 2:i])
if 10 <= two <= 26: cur += prev2
prev2, prev1 = prev1, cur
return prev1Tips
- A leading "0" by itself can never be decoded, since there is no letter for 0.
- "06" is not a valid two-digit code either: only 10 through 26 are.
In the .NET library
A string with a stray 0, like "100", can decode to zero ways even though it looks harmless; "0" only works as the second half of "10" or "20", never alone.