Advertisement
imashutosh51

Total Decoding Messages

Oct 6th, 2022 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. /*
  2. eg 213
  3. lets think about last 3
  4. Generally there is only two possibilites:
  5. i) either ith char can be attacted to all decoded strings till i-1th character eg. 3 can be attached to 1 and make as 21,3 or 2,1,3
  6. ii)or ith char can be attached to i-2th character and (i-1th+ith) as one character eg 3 can be attached to 1 as 2,13
  7.  
  8. so an array will be required to apply dynamic programing.
  9. Now conditions:-
  10. Four conditions are possible as per the i-1th and ith character:
  11. i)00
  12. ii)0 non-zero
  13. iii)non-zero 0
  14. iv)non-zero non-zero
  15. */
  16. #include<stdio.h>
  17. #include<bits/stdc++.h>
  18. #define lli unsigned long long int
  19. lli m=pow(10,9)+7;
  20. using namespace std;
  21. class Solution {
  22.     public:
  23.         lli CountWays(string s){
  24.         if(s[0]=='0') return 0;
  25.         if(s.size()==1) return 1;
  26.         lli dp[s.size()+1];
  27.         dp[0]=1;
  28.         for(int i=1;i<s.size();i++){
  29.             if(s[i-1]=='0' && s[i]=='0'){
  30.                   return 0;
  31.             }    
  32.             else if(s[i-1]=='0' && s[i]!='0'){
  33.                 dp[i]=dp[i-1];
  34.             }
  35.             else if(s[i-1]!='0' && s[i]=='0'){
  36.                 string temp=""; temp.push_back(s[i-1]);temp.push_back(s[i]);
  37.                 if(i-2>=0 && stoi(temp)<=26) dp[i]=dp[i-2];  //i-2>=0 to avoid first two character string
  38.                 else if(stoi(temp)<=26) dp[i]=1;
  39.                 else return 0;
  40.             }
  41.             else{
  42.                 string temp="";
  43.                 temp.push_back(s[i-1]); temp.push_back(s[i]);
  44.                 if(i-2>=0 && stoi(temp)<=26) dp[i]=(dp[i-2]+dp[i-1])%m;  //i-2>=0 to avoid first two character stringstring.
  45.                 else if(stoi(temp)<=26) dp[i]=2; //because for two character lesser than 26 ie. 23 can make 2 possiblities ie. bc and x.
  46.                 else dp[i]=dp[i-1];
  47.             }
  48.         }
  49.         return dp[s.size()-1];
  50.         }
  51.  
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement