leecode 解题总结:44. Wildcard Matching

#include 
#include 
#include 

using namespace std;
/*
问题:
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

分析:
wildcard:通配符.?可以匹配任意单一字符,*匹配任意字符串(包括空字符串)
关键是如何进行查询,可以将两个字符串逐一取出字符进行比较。
主串与模式串字符相同,则各自继续查找下一个字符;
如果模式串此时为'?',那么表示肯定匹配,只要主串当前字符不空,则继续各自向下查找;
如果模式串此时为"*",判断如果模式串后面没有字符了,直接返回true
否则,模式串后面有字符,就继续寻找到下一个不是'*'的字符。难点就在这里如何进行处理。
aab, *a*b
无法解出。



输入:
aab(主串) *a*b(模式串)
aa a
aa aa
aaa aa
aa *
aa a*
ab ?*
aab c*a*b
输出:
true
false
true
false
true
true
true
true

关键:
1 正确解法:
1】当遇到主串和模式串相等字符或模式串对应字符为"?",则主串指针s和模式串指针p都累加;
2】否则,两者不等,模式串为"*"时,遇到*号的时候,需要记录当前主串位置match,以及模式串中*的位置startIndex,
                                   让模式串指针p累加;
                   当前模式串不为"*"时,但上次模式串有"*"可用,此时需要回溯。令模式串指针p=上次记录的*位置 + 1,令主串match++,并令
					               主串指针s等于下一个字符
					如果两个字符都不相等,且无上次的"*"可用,说明不匹配
	最终模式串指针p应该等于模式串长度,说明完全匹配

2 		while(sIndex < lenS)//这里模式串的条件不能放在这里,必须放入后续条件张,一旦无法比较,返回false
		{
			//如果两个字符相等,或者模式串中含有"*"
			if(pIndex < lenP && ( s.at(sIndex) == p.at(pIndex) || p.at(pIndex) == '?' ) )
*/

class Solution {
public:
    bool isMatch(string s, string p) {
		int pIndex = 0;
		int lenP = p.length();
		int sIndex = 0;
		int lenS = s.length();
		int starIndex = -1;//记录'*'的位置,会用于回溯
		int match = 0;
		while(sIndex < lenS)//这里模式串的条件不能放在这里,必须放入后续条件张,一旦无法比较,返回false
		{
			//如果两个字符相等,或者模式串中含有"*"
			if(pIndex < lenP && ( s.at(sIndex) == p.at(pIndex) || p.at(pIndex) == '?' ) )
			{
				sIndex++;
				pIndex++;
			}
			//如果模式串中为"*",则记录'*'的位置,并只累加模式串的指针,主串指针不走
			else if(pIndex < lenP &&  '*' == p.at(pIndex))
			{
				starIndex = pIndex;
				match = sIndex;//记录上次匹配的位置
				pIndex++;
			}
			//如果此时主串与模式串不等,但是还有'*'可以用于替换,则主串回到匹配位置+1的位置处,而模式串的位置则回到上次'*'位置+1处
			else if(starIndex != -1)
			{
				match++;
				sIndex = match;
				pIndex = starIndex + 1;
			}
			//如果主串与模式串不等,且没有'*'可代替,则必定不等
			else
			{
				return false;
			}
		}
		//判断模式串是否走到末尾
		while( pIndex < lenP && p.at(pIndex) == '*' )
		{
			pIndex++;
		}
		return pIndex == lenP;
    }
};

void process()
{
	string s;
	string pattern;
	Solution solution;
	while(cin >> s >> pattern)
	{
		bool flag = solution.isMatch(s , pattern);
		cout << flag << endl;
	}
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}

你可能感兴趣的:(leecode)