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.
主要是要区分当最后一位是0时
动态规划,保存没一个字符时的情况
int numDecodings(char* s) { int len = strlen(s); // if no num or first num is 0, return 0 if(len == 0 || *s == '0') return 0; // else open space with len + 1 size ,named num int *num = (int *)malloc((len + 1) * sizeof(int)); num[0] = 1; num[1] = 1; // go over the string for(int i = 1; i < len; i++){ // if the cur char is 0, if(s[i] == '0'){ //if the pre char no be 1 or 2 ,return 0 if(s[i - 1] == '0' || s[i - 1] > '2') return 0; // else num is pre pre num else num[i + 1] = num[i - 1]; } // else if the pre char & cur char is between 11 to 26 , the num be the sum of pre and prepre num else if(s[i - 1] == '1' || (s[i -1] == '2' && s[i] <= '6')) num[i + 1] = num[i] + num[i - 1]; // else other chars while be the previous num else num[i + 1] = num[i]; } //return last num return num[len]; }