Decode Ways leetcode - Ryan的修炼之路
Decode Ways
A message containing letters from A-Z is being encoded to numbers
using the following mapping:'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing
digits, determine the total number of ways to decode it.For example, Given encoded message "12", it could be decoded as "AB"
(1 2) or "L" (12).The number of ways decoding "12" is 2.
动态规划
说明
state: dp[i]表示前i个字符的总共decode的可能性
function:
如果第i个字符(substring[i-1,i] )可以被decode, dp[i] = dp[i-1]
如果i-1, i字符(substring[i-2,i-1])可以decode, dp[i] += dp[i-1]
inital: dp[0] = 1 因为当长度为2时候找第二种情况就等于dp[0], 此时应该为1而不是0
dp[1] = 0 或者1 之所以要定义dp[1]因为我们要判定i-2的情况 所以单独列出来return dp[s.length()]
复杂度
时间复杂度O(n), 空间O(n)
代码
public int numDecodings(String s) { if (s == null || s.length() == 0) { return 0; } int[] dp = new int[s.length() + 1]; dp[0] = 1; dp[1] = isValid(s.substring(0, 1))? 1 : 0; for (int i = 2; i <= s.length(); i++) { if (isValid(s.substring(i - 1, i))) {dp[i] += dp[i - 1]; } if (isValid(s.substring(i - 2, i))) {dp[i] += dp[i - 2]; } } return dp[s.length()];}public boolean isValid(String s) { if (s == null || s.length() == 0) { return false; } if (s.charAt(0) == '0') { return false; } int tem = Integer.parseInt(s);//把string变为int return tem >= 1 && tem <= 26;}
复杂度
时间复杂度O(n), 空间O(1)
说明
因为每次计算i只用到i之前的两个数
所以这里可以只用一个容量为3的数组, 每次i存在[i%3]对应的位置
代码
public int numDecodings(String s) { if (s == null || s.length() == 0) { return 0; } int[] dp = new int[3]; dp[0] = 1; dp[1] = isValid(s.substring(0, 1))? 1 : 0; for (int i = 2; i <= s.length(); i++) { dp[i % 3] = 0; if (isValid(s.substring(i - 1, i))) {dp[i % 3] += dp[(i - 1) % 3]; } if (isValid(s.substring(i - 2, i))) {dp[i % 3] += dp[(i - 2) % 3]; } } return dp[s.length() % 3];}public boolean isValid(String s) { if (s == null || s.length() == 0) { return false; } if (s.charAt(0) == '0') { return false; } int tem = Integer.parseInt(s);//把string变为int return tem >= 1 && tem <= 26;}