首页 > 代码库 > [leetcode] Decode Ways
[leetcode] 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.
https://oj.leetcode.com/problems/decode-ways/
思路1:dfs。
思路2:dp。类似斐波那契数列,dp[i]表示从头到i位共有多少中组合。
如果i-1位不等于0,则dp[i]需要加上dp[i-1]的情况。
如果i-2位到i-1位在1-26之间,则dp[i]需要加上dp[i-2]情况。
public class Solution { // be careful of "0" "01" "100" public int numDecodings(String s) { if (s.length() == 0) return 0; int[] dp = new int[s.length() + 1]; dp[0] = 1; if (s.charAt(0) != ‘0‘) dp[1] = 1; else dp[1] = 0; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) != ‘0‘) dp[i + 1] = dp[i]; if (s.charAt(i - 1) != ‘0‘ && Integer.parseInt(s.substring(i - 1, i + 1)) <= 26) dp[i + 1] += dp[i - 1]; } return dp[s.length()]; } public static void main(String[] args) { String s = "1010"; System.out.println(new Solution().numDecodings(s)); }}
参考:
http://blog.csdn.net/u011095253/article/details/9248109
http://blog.csdn.net/worldwindjp/article/details/19938131
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。