91. Decode Ways
Description
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).
Solution
给一个数字的字符串,判断这个字符串可以代表多少种字母的表示方式。非常经典的动态规划题目。
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.
Code
class Solution {
public int numDecodings(String s) {
if (s.length() == 0)
return 0;
int len = s.length();
int[] dp = new int[len + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= len; i++){
int first = Integer.valueOf(s.substring(i - 1, i));
int second = Integer.valueOf(s.substring(i - 2, i));
if (first > 0 && first < 10)
dp[i] += dp[i-1];
if (second >= 10 && second <= 26)
dp[i] += dp[i-2];
}
return dp[len];
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Review
This problem can also be solved by O(1) space complexity.
推荐阅读
-
php中html_entity_decode实现HTML实体转义
-
oracle的decode()含义及使用介绍
-
php5.2以下版本无json_decode函数的解决方法
-
Oracle DECODE函数语法使用介绍
-
Oracle Decode()函数使用技巧分享
-
使用Oracle的Decode函数进行多值判断
-
Oracle中decode函数用法
-
RLException: Invalid <node> tag: ‘ascii‘ codec can‘t decode byte 0xe6报错
-
Anaconda中启动Python时的错误:UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 553
-
简单介绍Python中的decode()方法的使用