[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

这题比较复杂,最后用一种比较 naive 的思想解决。

假设 str 1 为 AB,str 2 为 A*C。

在 B 中一位位地找有没有 C 出现。

举例:匹配 aabcd 与 *abcd

一开始第一个 a 与 a 匹配,但是第二个 a 与 b 不匹配;于是将指针退回,指向第二个 a 和 a。


代码参考: http://fisherlei.blogspot.com/2013/01/leetcode-wildcard-matching.html 


class Solution {
public:
    bool isMatch(const char *s, const char *p) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		bool starFlag = false;
		const char *strS, *strP;
		for(strS = s,strP = p; *strS!='\0';strS++,strP++)
		{
			switch(*strP)
			{
			case '?': 
				break;

			case '*':
				{
					starFlag = true;
					s = strS;
					p = strP;
					while(*p=='*')
					{
						p++;//n个*等价于一个*                    
					}
					if(*p=='\0')//剪枝
					{
						return true;
					}                    
					strS = s-1;
					strP = p-1;
					break;
				}               

			default:
				{
					if(*strP!=*strS)
					{
						if(!starFlag)//之前没有出现过*,那么直接返回false
						{
							return false;
						}
						else
						{
							s++;
							strP = p-1;//指针退回                            
							strS = s-1;//指针退回                            
						}
					}
				}
			}

		}
		while(*strP=='*')
		{
			strP++;//结尾的*也需要处理掉
		}

		return (*strP=='\0')?true:false;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值