Q91. Decode Ways
Last updated
Was this helpful?
Last updated
Was this helpful?
直达:
A message containing letters fromA-Z
is being encoded to numbers using the following mapping:
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.
当遍历到字符串 s 的第k个位置时,对应的路径的数量取决于第k-1和k-2个位置的内容和路径数。所以要采用动态规划求解,具体要分成下面几种情况:
s[i] == 0
如果0<(s[i-1]-'0')*10+s[i]-'0'<=26
, 则第k个位置的路径数等于第k-2个位置的路径数, 例如*10*
,要从左侧*
处断开;
反之,路径数为0,例如*30*
.无法继续,路径数为0,直接返回0。
s[i] != 0
如果s[i-1]==0
如果0<(s[i-1]-'0')*10+s[i]-'0'<=26
,则第k个位置的路径数等于第k-1个位置的路径数;
否则,路径数为0,直接返回,如*00*
这种情况
如果s[i-1] != 0
如果0<(s[i-1]-'0')*10+s[i]-'0'<=26
,则第k个位置的路径数等于第k-1个位置的路径数加上k-2个位置的路径数,如*123*
,i指向3,断成*12,3*
或者*1,23*
都可以;
否则,则第k个位置的路径数等于第k-1个位置的路径数,如*128*
只能断成*12,8*
。