A message containing letters from A-Z is being encoded to numbers using the following mapping:
‘A’ -> 1 ‘B’ -> 2 … ‘Z’ -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: “12” Output: 2 Explanation: It could be decoded as “AB” (1 2) or “L” (12).
Example 2:
Input: “226” Output: 3 Explanation: It could be decoded as “BZ” (2 26), “VF” (22 6), or “BBF” (2 2 6).
Problem URL
给一个数字的字符串,判断这个字符串可以代表多少种字母的表示方式。非常经典的动态规划题目。
We could use dynamic programming to resolve this problem. Using an array with length of s’s length add one to store dynamic programming result. dp[0] = 1; value of dp[1] is depended on the first char of s is valid or not. Then we could start our dynamic programming in a for loop. Using Integer.valueOf() to get the number of one digit and two digits before dp[] posision. Then determining whether it is valid or not. If valid, dp should contain the value of one or two digit before. Finally, return dp[n], which is the answer.
Time Complexity: O(n) Space Complexity: O(n)
This problem can also be solved by O(1) space complexity.