leetcode之萬用字元

fangjian1204發表於2014-08-18

Wildcard 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
思路:本題和上面不同之處在於,此時的萬用字元'*'和它前面的字元看成一個整體,它們兩個代表0到多個第一個字元,而不是任一個字元。所以,當下一個字元是'*'時,如果當前字元相等,則反覆跳過當前字元去匹配'*'後面的字元,如果不相等,則直接匹配'*'後面的字元。
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;
    }
};



相關文章