Wildcard Matching @LeetCode

PROBLEM :

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") ? false
isMatch("aa","aa") ? true
isMatch("aaa","aa") ? false
isMatch("aa", "*") ? true
isMatch("aa", "a*") ? true
isMatch("ab", "?*") ? true
isMatch("aab", "c*a*b") ? false

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

class Solution {
public:
    bool isMatch(string str, string pattern) {
        int l1,l2 ;
        l1=str.length() ;
        l2=pattern.length() ;
   
        if(!l1&&!l2)
            return true ;
       
        if(!l2)
            return false ;
       
        bool lookup[l1+1][l2+1] ;
        memset(lookup, false, sizeof(lookup));
       
        lookup[0][0]=true ;
   
        for(int i=1;i<=l2;i++)
            if(pattern[i-1]=='*')
                lookup[0][i]=lookup[0][i-1] ;
           
        for(int i=1;i<=l1;i++)
        {
            for(int j=1;j<=l2;j++)
            {
                if(pattern[j-1]=='*')
                    lookup[i][j]=(lookup[i-1][j]||lookup[i][j-1]) ;
               
                else if(pattern[j-1]=='?'||pattern[j-1]==str[i-1])
                    lookup[i][j]=lookup[i-1][j-1] ;
               
                else
                    lookup[i][j]=false ;
            }
        }
   
        return lookup[l1][l2] ;
    }
};

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )