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

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.

 1 public static int DecodeWays(string s)

 2         {

 3             if (s[0] == '0' || s.Length == 0) //如果第一个character是'0',或者s长度为0,返回0

 4                 return 0;

 5 

 6             int[] ret = new int[3];

 7             ret[0] = 1;

 8             ret[1] = 1;

 9 

10             for (int i = 1; i < s.Length; i++)

11             {

12                 if (s[i - 1] == '0' && s[i] == '0') //Validation 如果有违法字符,直接返回0

13                     return 0;

14                 if (s[i] == '0' && s[i - 1] >= '3') //Validation 如果有违法字符,直接返回0

15                     return 0;

16 

17                 if (s[i] == '0') //如果s[i] == '0',一定要和前一个字符组合,所以=ret[(i - 1) % 3]

18                         ret[(i + 1) % 3] = ret[(i - 1) % 3];

19                 else

20                 {

21                     string stemp = s[i - 1].ToString() + s[i].ToString();

22                     int temp = int.Parse(stemp);

23                     ret[(i + 1) % 3] = ret[i % 3] + (temp >= 10 && temp <= 26 ? ret[(i - 1) % 3] : 0); //如果与前一个字符能合法组成,结果就是前一个结果加上再前一个结果

24                 }

25             }

26 

27             return ret[s.Length % 3];

28         }

代码分析:

  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

你可能感兴趣的:(LeetCode)