Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- eg 213
- lets think about last 3
- Generally there is only two possibilites:
- 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
- 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
- so an array will be required to apply dynamic programing.
- Now conditions:-
- Four conditions are possible as per the i-1th and ith character:
- i)00
- ii)0 non-zero
- iii)non-zero 0
- iv)non-zero non-zero
- */
- #include<stdio.h>
- #include<bits/stdc++.h>
- #define lli unsigned long long int
- lli m=pow(10,9)+7;
- using namespace std;
- class Solution {
- public:
- lli CountWays(string s){
- if(s[0]=='0') return 0;
- if(s.size()==1) return 1;
- lli dp[s.size()+1];
- dp[0]=1;
- for(int i=1;i<s.size();i++){
- if(s[i-1]=='0' && s[i]=='0'){
- return 0;
- }
- else if(s[i-1]=='0' && s[i]!='0'){
- dp[i]=dp[i-1];
- }
- else if(s[i-1]!='0' && s[i]=='0'){
- string temp=""; temp.push_back(s[i-1]);temp.push_back(s[i]);
- if(i-2>=0 && stoi(temp)<=26) dp[i]=dp[i-2]; //i-2>=0 to avoid first two character string
- else if(stoi(temp)<=26) dp[i]=1;
- else return 0;
- }
- else{
- string temp="";
- temp.push_back(s[i-1]); temp.push_back(s[i]);
- 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.
- 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.
- else dp[i]=dp[i-1];
- }
- }
- return dp[s.size()-1];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement