Sunday, July 2, 2017

Decode Ways

A top-secret message string S containing letters from A-Z (only upper-case letters) is encoded to numbers using the following mapping: 'A' -> 1, 'B' -> 2 and so on till Z -> '26' The program has to print the total number of ways in which the received message can be decoded.

Input Format:

The first line contains the string S containing numbers.

Output Format:

The first line contains the number of ways in which S can be decoded.

Boundary Conditions: 1 <= Length of S <= 100

Example Input/Output 1:

Input:

123

Output:

3

Explanation:

1-A 2-B 3-C 12-L 23-W. Hence 123 can be decoded as ABC or AW or LC, that is in 3 ways.

Example Input/Output 2:

Input:

1290

Output:

0

Solution: 

s = input()
l = len(s)
w = [1,0,0]
for i in range(l-1,-1,-1):
    w[2] = w[1]
    w[1] = w[0]
    w[0] = 0
    if i<l and s[i]!='0':
        w[0]+=w[1]
    if i+1<l and (s[i]=='1' or (s[i]=='2' and s[i+1]<'7')):
        w[0]+=w[2]

print(w[0])
Share: