Skip to content

Commit e578694

Browse files
committed
解码方法
1 parent 2dc5abb commit e578694

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

decode_ways.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param {string} s a string, encoded message
5+
# @return {int} an integer, the number of ways decoding
6+
def numDecodings(self, s):
7+
# Write your code here
8+
'''
9+
从后往前找,对于第i位的情况:
10+
1. 等于第i + 1位的组合。
11+
2. 如果s[i][i + 1]在10到26的范围内,再加上第i + 2位的组合。
12+
'''
13+
if not s:
14+
return 0
15+
cached_nums = [1 for i in xrange(len(s) + 1)] # 多一格方便处理倒数第二位的情况
16+
for i in xrange(len(s) - 1, -1, -1):
17+
if s[i] == '0':
18+
cached_nums[i] = 0
19+
else:
20+
cached_nums[i] = cached_nums[i + 1]
21+
if i < len(s) - 1:
22+
if (s[i] == '1') or ((s[i] == '2') and (s[i + 1] <= '6')):
23+
cached_nums[i] += cached_nums[i + 2]
24+
return cached_nums[0]

0 commit comments

Comments
 (0)