摘要:用将子字符串转化为,参见和的区别然后用动规方法表示字符串的前位到包含方法的个数。最后返回对应字符串末位的动规结果。
Problem
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.
ExampleGiven encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.
用parseInt将子字符串转化为int,参见parseInt和valueOf的区别;
然后用动规方法:
dp[i]表示字符串s的前i位(0到i-1)包含decode方法的个数。
若前一位i-2到当前位i-1的两位字符串s.substring(i-2, i)对应的数字lastTwo在10到26之间,则当前位dp[i]要加上这两位字符之前一个字符对应的可能性:dp[i-2];
若当前位i-1的字符对应1到9之间的数字(不为0),则当前dp[i]要加上前一位也就是第i-2位的可能性:dp[i-1]。
最后返回对应字符串s末位的动规结果dp[n]。
class Solution { public int numDecodings(String s) { if (s == null || s.length() == 0) return 0; int n = s.length(); int[] dp = new int[n+1]; dp[0] = 1; //if the first two digits in [10, 26] dp[1] = s.charAt(0) == "0" ? 0 : 1; for (int i = 2; i <= n; i++) { if (s.charAt(i-1) != "0") dp[i] += dp[i-1]; //XXX5X int lastTwo = Integer.parseInt(s.substring(i-2, i)); if (lastTwo >= 10 && lastTwo <= 26) dp[i] += dp[i-2]; //XXX10X } return dp[n]; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65974.html
摘要:建立动规数组,表示从起点处到达该点的可能性。循环结束后,数组对所有点作为终点的可能性都进行了赋值。和的不同在于找到最少的步数。此时的一定是满足条件的最小的,所以一定是最优解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...
摘要:这里要注意的是的用法。所以记住,用可以从自动分离出数组。跳过第一个元素并放入数组最快捷语句建立的用意记录处理过的结点并按处理所有结点和自己的连接下面先通过判断,再修改的符号的顺序,十分巧妙更轻便的解法 Problem Design an algorithm and write code to serialize and deserialize a binary tree. Writin...
A message containing letters from A-Z is being encoded to numbers using the following A -> 1 B -> 2 ... Z -> 26 For example, Given encoded message 12, it could be decoded as AB (1 2) or L (12). The n...
Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...
Problem Implement a stack with min() function, which will return the smallest number in the stack. It should support push, pop and min operation all in O(1) cost. Example push(1)pop() // return 1pus...
阅读 1165·2021-11-23 09:51
阅读 1962·2021-10-08 10:05
阅读 2302·2019-08-30 15:56
阅读 1815·2019-08-30 15:55
阅读 2624·2019-08-30 15:55
阅读 2451·2019-08-30 13:53
阅读 3457·2019-08-30 12:52
阅读 1227·2019-08-29 10:57