Advertisement
imashutosh51

Wildcard Pattern Matching

Aug 14th, 2022 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6.  
  7. /*
  8. Logic:
  9. we will traverse the string from backside.
  10. ->There is three case possible here:
  11. i)pattern and string current character matches,so match for rest string ie. n-1,m-1
  12. ii)pattern current character is '?',which is equivalent to any one character,
  13.    same as case 1 so so match for rest string. ie. n-1,m-1
  14. iii)pattern current character is '*',so either * can be empty character or
  15.     some character.
  16.     a)empty character:so character index will be decreased.
  17.     b)some character:so decrease string index only,so pattern index is still
  18.       pointing to same '*',so same both condition arises again.In this
  19.       way,all 3 cases,no character,one character and some character will
  20.       be covered.
  21. */
  22. bool fun(string s,string pat,int n,int m,vector<vector <int>> &dp){
  23.     if(n==-1 && m==-1) return true;  //both string and pattern fully traversed so return 1.
  24.    
  25.     if(n==-1){                           // so string is empty but pattern is left,so pattern can be only * where
  26.         while(m>=0 && pat[m]=='*') m--;  //all * will be replaced with empty character and string will be macthed.
  27.         if(m==-1) return true;          
  28.         return false;
  29.     }
  30.     if(m==-1) return false;  //if m==-1 but n is not -1,means pattern ended,so false.
  31.     if(dp[n][m]!=-1) return dp[n][m];  
  32.     if(s[n]==pat[m] || pat[m]=='?') return dp[n][m]=fun(s,pat,n-1,m-1,dp);  //charcater matched in both condition.
  33.     if(pat[m]=='*'){
  34.         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.
  35.     }
  36.     return dp[n][m]=0;   //else return 0.
  37. }
  38. class Solution{
  39.   public:
  40.     int wildCard(string pattern,string str){
  41.         int n=str.size();
  42.         int m=pattern.size();
  43.         vector<vector<int>>dp(n+1,vector<int>(m+1,-1));
  44.         fun(str,pattern,n-1,m-1,dp);
  45.         return dp[n-1][m-1];
  46.     }
  47. };
  48.  
  49. //{ Driver Code Starts.
  50. int main()
  51. {
  52.    int t;
  53.    cin>>t;
  54.    while(t--)
  55.    {
  56.            string pat,text;
  57.            cin>>pat;
  58. cin.ignore(numeric_limits<streamsize>::max(),'\n');
  59.            cin>>text;
  60.            Solution obj;
  61.            cout<<obj.wildCard(pat,text)<<endl;
  62.    }
  63. }
  64.  
  65. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement