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
class Solution {
public:
bool isMatch(const char *s, const char *p)
{
int len1=strlen(p);
int len2=strlen(s);
//consider the last case.....
int len=len1;
for(int i=0;i<len1;i++)
if(p[i]=='*') len--;
if(len>len2) return 0;
bool* match=new bool[len2+1];
for(int j=1;j<=len2;j++) match[j]=false;
match[0]=true;
for(int i=1;i<=len1;i++)
{
if(p[i-1]=='*')
{
for(int j=1;j<=len2;j++)
{
if(match[j-1]) match[j]=true;
}
}
else if(p[i-1]=='?')
for(int j=len2;j>=1;j--)
{
if(match[j-1]) match[j]=true;
else match[j]=false;
}
else
for(int j=len2;j>=1;j--)
{
if(match[j-1] && p[i-1]==s[j-1]) match[j]=true;
else match[j]=false;
}
if(match[0] && p[i-1]=='*') match[0]=true;
else match[0]=false;
}
return match[len2];
}
};
public:
bool isMatch(const char *s, const char *p)
{
int len1=strlen(p);
int len2=strlen(s);
//consider the last case.....
int len=len1;
for(int i=0;i<len1;i++)
if(p[i]=='*') len--;
if(len>len2) return 0;
bool* match=new bool[len2+1];
for(int j=1;j<=len2;j++) match[j]=false;
match[0]=true;
for(int i=1;i<=len1;i++)
{
if(p[i-1]=='*')
{
for(int j=1;j<=len2;j++)
{
if(match[j-1]) match[j]=true;
}
}
else if(p[i-1]=='?')
for(int j=len2;j>=1;j--)
{
if(match[j-1]) match[j]=true;
else match[j]=false;
}
else
for(int j=len2;j>=1;j--)
{
if(match[j-1] && p[i-1]==s[j-1]) match[j]=true;
else match[j]=false;
}
if(match[0] && p[i-1]=='*') match[0]=true;
else match[0]=false;
}
return match[len2];
}
};