jayati

Regular Expression Matching

Oct 9th, 2022 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool f(int i,int j,string &s,string &p)
  4.     {
  5.         if(i<0 && j<0) return true;   //Both Strings Exhausted
  6.         if(j<0 && i>=0) return false;  //p exhausted but s is remaining
  7.         if(i<0 && j>=0)  //if s is exhausted by p remains , it will only be true if all charcter in p have *;
  8.         {
  9.             while(j>=0)
  10.             {
  11.                 if(p[j]=='*') j-=2;
  12.                 else return false;
  13.             }
  14.             return true;
  15.         }
  16.        
  17.         if(p[j]==s[i] || p[j]=='.') return f(i-1,j-1,s,p);
  18.        
  19.         if(p[j]=='*')
  20.         {
  21.             if(p[j-1]!=s[i] && p[j-1]!='.')
  22.                 return f(i,j-2,s,p);  //Consider * to be empty
  23.             else
  24.             {
  25.                 return f(i,j-2,s,p) || f(i-1,j,s,p);
  26.                 //These three case are as follows
  27.                 //consider * empty
  28.                 //consider * length>=1
  29.             }
  30.         }
  31.         return false;
  32.     }
  33.    
  34.     bool isMatch(string s, string p) {
  35.         int n=s.length(),m=p.length();
  36.         return f(n-1,m-1,s,p);
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment