Middle-题目124：91. Decode Ways

50人阅读 评论(0)

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.

dp[i] = dp[i-1] (s[i]<’9’ && s[i]>’0’)
dp[i-1]+dp[i-2] (“00”<s[i-1]+s[i]<”27”)

public class Solution {
public int numDecodings(String s) {
if(s.length() == 0) return 0;
if(s.charAt(0) == '0') return 0;
if(s.length() == 1) return s.charAt(0) > '0' ? 1:0;
int dp[] = new int[s.length()+1];
dp[0] = dp[1] = 1;
for(int i=2; i<=s.length(); i++){
dp[i] = dp[i-1];
if(s.charAt(i-1) == '0')
if (s.charAt(i-2) == '1' || s.charAt(i-2) == '2')
dp[i] = dp[i-2];
else return 0;
else if(s.charAt(i-2) == '0'){
dp[i] = dp[i-1];
}
else if(s.charAt(i-2) == '1' || (s.charAt(i-2) == '2' && s.charAt(i-1) < '7') )
dp[i] += dp[i-2];
}
return dp[s.length()];
}
}

2ms,beats 70.90%，众数5ms,26.83%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56311次
• 积分：3204
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论