leetcode之通配符

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;
    }
};



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值