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