[Leetcode] Decode Ways - python
A message containing letters from
Given an encoded message containing digits, determine the total number of ways to decode it.
For example, Given encoded message
The number of ways decoding
この問題は完全に詳細な問題で、「00」、「0」、「1212」、「1234」などのいくつかのデータを簡単に列挙すると、法則を出すことができます.
後から前へ処理し、i位に処理すると、
1、現在のビットと後のビットがともに0の場合、0を返します.
2、現在のビットと後のビットを組み合わせることができず、例えば'34'、counts[i]=counts[i+1]
3、現在のビットと後のビットを組み合わせることができる場合、counts[i]=counts[i+1]+counts[i+2]
初期化counts[len(s)]=1
コードは次のとおりです.
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. この問題は完全に詳細な問題で、「00」、「0」、「1212」、「1234」などのいくつかのデータを簡単に列挙すると、法則を出すことができます.
後から前へ処理し、i位に処理すると、
1、現在のビットと後のビットがともに0の場合、0を返します.
2、現在のビットと後のビットを組み合わせることができず、例えば'34'、counts[i]=counts[i+1]
3、現在のビットと後のビットを組み合わせることができる場合、counts[i]=counts[i+1]+counts[i+2]
初期化counts[len(s)]=1
コードは次のとおりです.
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if len(s)<1 or s[0]=='0':
return 0
counts={}
counts[len(s)]=1
if s[-1]=='0':
counts[len(s)-1]=0
else:
counts[len(s)-1]=1
for i in xrange(len(s)-2,-1,-1):
if s[i]=='0' :
if s[i+1]=='0':
return 0
else:
counts[i]=0
elif int(s[i])<3 and int(s[i])>0 and int(s[i:i+2])<27 and int(s[i:i+2])>0:
counts[i]=counts[i+2]+counts[i+1]
else:
counts[i]=counts[i+1]
return counts[0]
a=Solution()
print a.numDecodings('10')