Created
June 4, 2020 19:03
-
-
Save m-khooryani/04fd277e5190172478d1b1753c1eb17c to your computer and use it in GitHub Desktop.
Count Possible Decoding
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
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. |
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 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