91. Decode Ways

来源:互联网 发布:网络加密方式有哪些 编辑:程序博客网 时间:2024/06/14 04:27

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.

可以说我的代码又臭又长了:

public class Solution {    public int numDecodings(String s) {        if (s.length() == 0 || s.charAt(0) == '0')return 0;else if (s.length() == 1)return 1;int[] dp = new int[s.length()];dp[0] = 1;int num = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0');if (num > 26) {if (num % 10 == 0)dp[1] = 0;elsedp[1] = 1;} else {if (num == 10 || num == 20)dp[1] = 1;elsedp[1] = 2;}int pre_num = s.charAt(1) - '0';for (int i = 2; i < s.length(); ++i) {int cur_num = s.charAt(i) - '0';pre_num = pre_num * 10 + cur_num;if (pre_num > 26) {if (pre_num % 10 == 0)return 0;elsedp[i] = dp[i - 1];} else if (pre_num >= 10 && pre_num <= 26) {if (pre_num == 10 || pre_num == 20)dp[i] = dp[i - 2];elsedp[i] = dp[i - 1] + dp[i - 2];} else if (pre_num > 0 && pre_num < 10)dp[i] = dp[i - 1];elsereturn 0;pre_num = cur_num;}return dp[s.length() - 1];    }}