Skip to content

Commit 89cb8b3

Browse files
committed
Adding Efficient Solution for Problem - 91 - Decode Ways
1 parent 62b259b commit 89cb8b3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Decode_Ways/EfficientSolution.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 91
6+
## Problem Name: Decode Ways
7+
##===================================
8+
#
9+
#A message containing letters from A-Z is being encoded to numbers using the following mapping:
10+
#
11+
#'A' -> 1
12+
#'B' -> 2
13+
#...
14+
#'Z' -> 26
15+
#Given a non-empty string containing only digits, determine the total number of ways to decode it.
16+
#
17+
#Example 1:
18+
#
19+
#Input: "12"
20+
#Output: 2
21+
#Explanation: It could be decoded as "AB" (1 2) or "L" (12).
22+
#
23+
#Example 2:
24+
#
25+
#Input: "226"
26+
#Output: 3
27+
#Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
28+
class Solution:
29+
def numDecodings(self, s):
30+
if len(s) == 0 or s[0] == '0': #Condition-check: If str is empty or 1st digit is zero
31+
return 0 #We return zero
32+
tmpA, tmpB = 1, 0 #Initialize tmpA, tmpB counter
33+
for i in range(len(s)): #Loop through string
34+
tmp = 0 #Initialize final counter tmp
35+
if s[i] != '0': #Condition-check: If str's 1st digit is not zero
36+
tmp = tmpA #Update tmp by assigining tmpA
37+
if i > 0 and (s[i - 1] == '1' or (s[i - 1] == '2' and s[i] <= '6')): #Condition-check: If i is greater than zero and previous digit is one or previous and current digit is between 2 and 6
38+
tmp += tmpB #Update tmp by adding tmpB into it
39+
tmpA, tmpB = tmp, tmpA #Update tmpA, and tmpB by assigining tmp and tmpA
40+
return tmpA #Return tmpA

0 commit comments

Comments
 (0)