您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Decode Way

2012-08-29 05:50 459 查看
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 static int DecodeWays(string s)
{
if (s[0] == '0' || s.Length == 0) //如果第一个character是'0',或者s长度为0,返回0
return 0;

int[] ret = new int[3];
ret[0] = 1;
ret[1] = 1;

for (int i = 1; i < s.Length; i++)
{
if (s[i - 1] == '0' && s[i] == '0') //Validation 如果有违法字符,直接返回0
return 0;
if (s[i] == '0' && s[i - 1] >= '3') //Validation 如果有违法字符,直接返回0
return 0;

if (s[i] == '0') //如果s[i] == '0',一定要和前一个字符组合,所以=ret[(i - 1) % 3]
ret[(i + 1) % 3] = ret[(i - 1) % 3];
else
{
string stemp = s[i - 1].ToString() + s[i].ToString();
int temp = int.Parse(stemp);
ret[(i + 1) % 3] = ret[i % 3] + (temp >= 10 && temp <= 26 ? ret[(i - 1) % 3] : 0); //如果与前一个字符能合法组成,结果就是前一个结果加上再前一个结果
}
}

return ret[s.Length % 3];
}


代码分析:

  DP思想:

  例如 : "1213104"

  “1” : 1

  "12" :1 + 1 = 2

  “121” : “1” + “12” = 1 + 2 = 3

  “1213” : “12” + “121” = 2 + 3 = 5 (可看成[”12“ + ‘13’] + ["121" + '3']

  ”12131“ : ”1213“ = 5 (因为 '31' > 26 违法了,所以只能看成["1213" + '1'] = “1213” = 5

  “121310” : “1213” = 5 (因为 ‘0’ 违法,所以只能看成["1213" + '10'] = "1213" = 5

  "1213104" : "121310" = 5 (因为'04' 违法,所以只能看成["121310" + '4'] = "121310" = 5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: