[抄题]:
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).
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
最后一位是空串对应翻译方法只有1种,为0时对应翻译方法为0
[思维问题]:
任何题目都试试dp
[一句话思路]:
从前往后切不好控制范围 不知道要切几次,因此从后往前切
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 从前往后时是小角标构成大角标,从后往前是大角标构成小角标
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
从前往后切不好控制范围 不知道要切几次,因此从后往前切
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
取出字符串长度2 包左不包右:
s.substring(i, i+2)
字符串转数字:
Integer.parseInt(字符串)
[算法思想:递归/分治/贪心]:贪心
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
639. Decode Ways II 有* dp
[代码风格] :
class Solution { public int numDecodings(String s) { //cc if (s.length() == 0) return 0; //ini n, n - 1 int n = s.length(); int[] nums = new int[n + 1]; nums[n] = 1;//预处理 nums[n - 1] = (s.charAt(n - 1) == '0') ? 0 : 1;//处理 //for loop for (int i = n - 2; i >= 0; i--) { if (s.charAt(i) == '0') continue; nums[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? nums[i + 2] + nums[i + 1] : nums[i + 1]; } return nums[0]; } }