Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- /*
- Logic:
- we will traverse the string from backside.
- ->There is three case possible here:
- i)pattern and string current character matches,so match for rest string ie. n-1,m-1
- ii)pattern current character is '?',which is equivalent to any one character,
- same as case 1 so so match for rest string. ie. n-1,m-1
- iii)pattern current character is '*',so either * can be empty character or
- some character.
- a)empty character:so character index will be decreased.
- b)some character:so decrease string index only,so pattern index is still
- pointing to same '*',so same both condition arises again.In this
- way,all 3 cases,no character,one character and some character will
- be covered.
- */
- bool fun(string s,string pat,int n,int m,vector<vector <int>> &dp){
- if(n==-1 && m==-1) return true; //both string and pattern fully traversed so return 1.
- if(n==-1){ // so string is empty but pattern is left,so pattern can be only * where
- while(m>=0 && pat[m]=='*') m--; //all * will be replaced with empty character and string will be macthed.
- if(m==-1) return true;
- return false;
- }
- if(m==-1) return false; //if m==-1 but n is not -1,means pattern ended,so false.
- if(dp[n][m]!=-1) return dp[n][m];
- if(s[n]==pat[m] || pat[m]=='?') return dp[n][m]=fun(s,pat,n-1,m-1,dp); //charcater matched in both condition.
- if(pat[m]=='*'){
- return dp[n][m]= (fun(s,pat,n-1,m,dp) || fun(s,pat,n,m-1,dp)); //so case iii) no or some charcater matched.
- }
- return dp[n][m]=0; //else return 0.
- }
- class Solution{
- public:
- int wildCard(string pattern,string str){
- int n=str.size();
- int m=pattern.size();
- vector<vector<int>>dp(n+1,vector<int>(m+1,-1));
- fun(str,pattern,n-1,m-1,dp);
- return dp[n-1][m-1];
- }
- };
- //{ Driver Code Starts.
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- string pat,text;
- cin>>pat;
- cin.ignore(numeric_limits<streamsize>::max(),'\n');
- cin>>text;
- Solution obj;
- cout<<obj.wildCard(pat,text)<<endl;
- }
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement