标签:wildcard matching regular expression m leetcode wildcard pattern matching
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) {
    	const char* sBegin = NULL,*pBegin = NULL;
    	while(*s)
    	{
    		if(*s == *p || *p == '?')
    		{
    			++s;
    			++p;
    		}
    		else if(*p == '*')
    		{
    			pBegin = p;//记录通配符的位置
    			sBegin = s;
    			++p;
    		}
    		else if(pBegin != NULL)
    		{
    			p = pBegin + 1;//重通配符的下一个字符开始
    			++sBegin;//每次多统配一个
    			s = sBegin;
    		}
    		else return false;
    	}
    	while(*p == '*')++p;
    	return (*p == '\0');
    }
};
Implement regular expression matching with support for ‘.‘ and ‘*‘.
‘.‘ Matches any single character.
‘*‘ Matches zero or more of the preceding element.
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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
class Solution {
public:
    bool isMatch(const char *s, const char *p) {
    	if(*p == '\0')return *s == '\0';
    	if(*(p+1) != '*')
    	{
    		if(*s != '\0' && (*s == *p || *p == '.'))return isMatch(s+1,p+1);
    	}
    	else 
    	{
    		//s向后移动0、1、2……分别和p+2进行匹配
    		while(*s != '\0' && (*s == *p || *p == '.'))
    		{
    			if(isMatch(s,p+2))return true;
    			++s;
    		}
    		return isMatch(s,p+2);
    	}
    	return false;
    }
};标签:wildcard matching regular expression m leetcode wildcard pattern matching
原文地址:http://blog.csdn.net/fangjian1204/article/details/38640615