91. Decode Ways
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "3"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
- "AAJF" with the grouping (1 1 10 6)
 - "KJF" with the grouping (11 10 6)
 
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example: 1
Input: s = "12"
Output: 2
Example: 2
Input: "226"
Output: 3
Example: 3
Input: "0"
Output: 0
- 1 <= s.length <= 100
 - s contains only digits and may contain leading zero(s).
 
- First of all we know that the numbers range from 1 to 26. So any number having no of digits greater than two can be discarded.
 - Also '0' cannot be taken as an element, because '0' has no mapping. It can only be considered if it is preceded by a '1' or '2'.
 - So we will mark in our boolean array: For every index 'i' can we take 1 position (i.e [i, i]) and can we take two positions (i.e [i, i + 1]).
 - If yes we will mark them true, otherwise false.
 - This is done in the code below.
 
- Now we will compute the result by considering [l, r] ranges.
 - If range [l, r] is valid, then we will compute result for ranges [l + 1, l + 1] and [l + 1, l + 2]. If it is invalid we can simply return 0, because this combination won't give us any answer.
 - Also if current range [l, r] is valid and 'r' equals the last index of string, then we can return 1.
 - One more condition to check is that, if 'r' exceeds the last index of string, since there isn't any character for combination, we can say that such string cannot exist. So we will return 0.
 - This step is shown in code below.
 
- Now for every state [l, r] we might be recomputing them again and again during recursion.
 - This can result into TLE.
 - So what we will do is, after computing value of [l, r] we will store it into dp array mapping them by [l, r].
 - This step is shown in code below.
 
Comments
Post a Comment
If you have any queries or need solution for any problem, please let me know.