Advertisement
adityaraj5200

Untitled

Jun 4th, 2025
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool isMatch(string s, string p) {
  4.         memset(dp,-1,sizeof(dp));
  5.         return solve(0,0,s,p);
  6.     }
  7. private:
  8.     int dp[21][21];
  9.     bool solve(int i,int j,string& s,string& p){
  10.         if(j==p.length()){
  11.             return i==s.length();
  12.         }
  13.  
  14.         bool asteriskAhead = (j+1<p.length()) && (p[j+1]=='*');
  15.  
  16.         if(i==s.length()){
  17.             return asteriskAhead && solve(i,j+2,s,p);
  18.         }
  19.  
  20.         if(dp[i][j] != -1) return dp[i][j];
  21.  
  22.         bool firstMatch = (i<s.length()) && (s[i]==p[j]) || (p[j] == '.');
  23.  
  24.         if(asteriskAhead){
  25.             bool zeroMatch = solve(i,j+2,s,p);
  26.             bool oneOrMoreMatch = firstMatch && solve(i+1,j,s,p);
  27.             return dp[i][j] = zeroMatch || oneOrMoreMatch;
  28.         }
  29.         else{
  30.             return dp[i][j] = firstMatch && solve(i+1,j+1,s,p);
  31.         }
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement