91. Decode Ways
problem desctiption
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26Given 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).algorithm thought
典型的动态规划问题,当前数字如果可以和前面数字组合成为一个合法的字符,当前decode way就可以加上前两次的decode way,如果当前的数字不等于0,就能加上前一个次的decode way。
code
algorithm analysis
一次遍历处理数组,时间复杂度O(n),使用一维数组保存结果,空间复杂度O(n)
Last updated