标签:empty 过程 ota eterm odi fir tput div amp
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).
解码方法。题意是给定一个只包含数字的非空字符串,请计算解码方法的总数。
思路是动态规划。这个题dp[i]的定义是前i个数字能产生的解码方法的总数。因为解码是从数字到字母,所以有效的数字就只能在1到26之间,所以
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int numDecodings(String s) { 3 // corner case 4 if (s == null || s.length() == 0) { 5 return 0; 6 } 7 8 // normal case 9 int n = s.length(); 10 int[] dp = new int[n + 1]; 11 dp[0] = 1; 12 dp[1] = s.charAt(0) != ‘0‘ ? 1 : 0; 13 for (int i = 2; i <= n; i++) { 14 int first = Integer.valueOf(s.substring(i - 1, i)); 15 int second = Integer.valueOf(s.substring(i - 2, i)); 16 if (first >= 1 && first <= 9) { 17 dp[i] += dp[i - 1]; 18 } 19 if (second >= 10 && second <= 26) { 20 dp[i] += dp[i - 2]; 21 } 22 } 23 return dp[n]; 24 } 25 }
标签:empty 过程 ota eterm odi fir tput div amp
原文地址:https://www.cnblogs.com/cnoodle/p/12940834.html