...
class Solution {
public:
long int dp[501][51][2];
const long int hell=1000000007;
long int helper(string &s,int st,bool flag,string s2,int p){
if(p>=s2.length())
return 0;
if(st>=s.length())
return 1;
if(dp[st][p][flag]!=-1)
return dp[st][p][flag];
long int ans=0,np;
for(char c='a';c<='z';c++){
np=c==s2[p]?p+1:0;
if(st==0){
if(c>s[st])
break;
if(c==s[st])
ans+=helper(s,st+1,true,s2,np);
else
ans+=helper(s,st+1,false,s2,np);
}
else{
if(flag){
if(c>s[st])
break;
else if(c==s[st])
ans+=helper(s,st+1,flag,s2,np);
else
ans+=helper(s,st+1,false,s2,np);
}
else
ans+=helper(s,st+1,false,s2,np);
}
ans%=hell;
}
return dp[st][p][flag]=ans;
}
int findGoodStrings(int n, string s1, string s2, string evil) {
if(s1>s2)
return 0;
long int ans1,ans2;
memset(dp,-1,sizeof dp);
ans2=helper(s2,0,false,evil,0);
memset(dp,-1,sizeof dp);
ans1=helper(s1,0,false,evil,0);
long int c=0;
if(s1.find(evil)==string :: npos)
c=1;
//cout<<ans2<<" "<<ans1<<" "<<ans2-ans1;
return (ans2-ans1+c+hell)%hell;
}
};
Note that usual answer to range query $$$[L,R]$$$ dynamic-programming counting problems should be $$$dp[R]-dp[L-1]$$$. Therefore, the answer should be subtracting the results of the two cases $$$s2$$$ and $$$prev(s1)$$$, where $$$prev(s1)$$$ is the previous $$$n$$$-letter lexicographically ordered string.
He added $$$c$$$ for the same.
I have a solution for this problem. Will explain in more detail in some time.
Short-explanation :-
1)First see how to count the number of strings between s1 and s2 . Let n1 = number of strings between (aaaaaaa...a and s1) , n2 = number of strings (aaaaa...aaaa and s2) , hence, answer = n2-n1+1 . (can be calculated easily with dp)
2)If you know how to do the step-1 , you will realize, that you only need to know, for each length-'i' (from aaaaa--->zzzzz(here, i = 5) , the number of strings which contains the substring "s3" atleast once, if you know it for length 'i' , transition to state 'i+1' is easy.
3)If you want the exact recurrence relations , I'll write them .
Did you left this one secrex__001 just because you become pupil in that? That much arrogance is not good for anyone.
For those who don't know about DFA I constructed a DFA for the string evil (i.e the DFA would reject all the strings which contains evil as a substring).
Then I used simple digit dp with two tights (t1,t2) for strings s1,s2 respectively and checked whether the the string is accepted by the DFA or not.
Here is my CODE it took 108ms to run(faster than all the codes submitted so far) Note the header files are missing as they are already included in leetcode's IDE.
Someone please help me.
On this testcase:
You code output's 25, but the answer is 24.