- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decode Ways in Python
Suppose we have a message containing letters from A to Z is being encoded to numbers using the following mapping − 'A' → 1, 'B' → 2 ... 'Z' → 26. So if we have one non-empty string, containing only digits, then we have to find, in how many ways that can be decoded. So if the string is like “12”, then that can be made from “AB”, or “L”, so there are two possible ways. So the answer will be 2.
To solve this, we will follow these steps −
- We will solve this using dynamic programming.
- n := length of s
- dp := an array with n number of 0s
- if s[0] is not ‘0’, then dp[0] := 1
- for i in range 1 to n – 1
- x := s[i] as integer, y := substring of s from index i – 1 to i + 1 as integer
- if x >= 1 and y <= 9, then dp[i] := dp[i] + dp[i – 1]
- if y >= 10 and y <= 26
- if i – 2 >= 0, then dp[i] := dp[i] + dp[i – 2], otherwise increase dp[i] by 1
- return last element of dp
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def numDecodings(self, s): n = len(s) dp = [0 for i in range(n)] if s[0]!='0': dp[0]=1 for i in range(1,n): x = int(s[i]) y = int(s[i-1:i+1]) if x>=1 and x<=9: dp[i]+=dp[i-1] if y>=10 and y<=26: if i-2>=0: dp[i]+=dp[i-2] else: dp[i]+=1 return dp[-1] ob1 = Solution() print(ob1.numDecodings("226"))
Input
"226"
Output
3
- Related Articles
- Decode Ways II in C++
- Program to find number of ways we can decode a message in Python
- Program to recover decode XORed array in Python
- Program to find decode XORed permutation in Python
- Encode and decode uuencode files using Python
- What is the difference between encode/decode in Python?
- Encode and decode binhex4 files using Python (binhex)
- Encode and decode XDR data using Python xdrlib
- Decode String in C++
- Encode and decode MIME quoted-printable data using Python
- Ways to concatenate tuples in Python
- Encode and Decode Strings in C++
- How can Tensorflow be used to decode the predictions using Python?
- Ways to increment a character in python
- Ways to print escape characters in python

Advertisements