imashutosh51

Total Decoding Messages

Oct 6th, 2022 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. '''
  2. eg 213
  3. Lets think about last character 3.
  4. Generally there are only two possibilities:
  5.  
  6. i) ith char can be attached separately to all decoded strings till i-1th character.
  7. eg. 3 can be attached separately and make:
  8. 21,3 or 2,1,3
  9.  
  10. ii) ith char can be combined with i-1th char and attached to all decoded strings till i-2th character.
  11. eg. 13 can be taken as one character and make:
  12. 2,13
  13. So a dp array is required to store previous answers.
  14. '''
  15.  
  16. #User function Template for python3
  17. class Solution:
  18.     def countWays(self, digits):
  19.         dp=[0]*len(digits)
  20.         dp[0]=1
  21.         for i in range(1,len(digits)):
  22.             if digits[i]!='0':
  23.                 dp[i]=dp[i-1]
  24.             if 10<=int(digits[i-1:i+1])<=26:
  25.                 dp[i]+=dp[i-2] if i>=2 else 1
  26.         return dp[-1]
  27.                
Advertisement
Add Comment
Please, Sign In to add comment