Skip to content

Instantly share code, notes, and snippets.

@m-khooryani
Created June 4, 2020 19:03
Show Gist options
  • Save m-khooryani/04fd277e5190172478d1b1753c1eb17c to your computer and use it in GitHub Desktop.
Save m-khooryani/04fd277e5190172478d1b1753c1eb17c to your computer and use it in GitHub Desktop.
Count Possible Decoding
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
class Program
{
static readonly Dictionary<string, long> memoized = new Dictionary<string, long>();
static void Main(string[] args)
{
Console.WriteLine(CountDecode("111"));
}
private static long CountDecode(string s)
{
if (string.IsNullOrWhiteSpace(s))
{
return 1L;
}
if (memoized.ContainsKey(s))
{
return memoized[s];
}
memoized.Add(s, CountDecode(s.Substring(1)));
if (s.Length > 1 && int.Parse(s.Substring(0, 2)) <= 26)
{
memoized[s] = memoized[s] + CountDecode(s.Substring(2));
}
return memoized[s];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment