Description:
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
分析:
通配符匹配过程中会有以下几种情况:
- s的字符和p的字符相等
- p中的字符是?,这时无论s的字符是什么都可以匹配一个
- p中遇到了一个*,这时无论s的字符是什么都没关系
- 之前的都不符合,但是p在之前的位置有一个* ,我们可以从上一个*后面开始匹配
- s已经匹配完,但是p后面还有很多连续的`*’
代码:
//递归
#include <iostream>
using namespace std;
bool isMatch(const char *s, const char *p)
{
if (*p == '\0')
return *s == '\0';
if ((*s == *p) || (*s != '\0' && *p == '?'))
{
return isMatch(s+1, p+1);
}
else if (*p == '*')
{
while (*p == '*')
p++; //跳过连续*
if (*p == '\0')
return true;
while (*s != '\0' && !isMatch(s, p))
s++;
return *s != '\0';
}
return false;
}
int main(int argc, char const *argv[]) {
char *s1 = "aa", *p1 = "a";
char *s2 = "aa", *p2 = "*";
char *s3 = "aa", *p3 = "a*";
char *s4 = "ab", *p4 = "?*";
char *s5 = "aab",*p5 = "c*a*b";
std::cout << boolalpha<<isMatch(s1, p1) << std::endl;
std::cout << boolalpha<<isMatch(s2, p2) << std::endl;
std::cout << boolalpha<<isMatch(s3, p3) << std::endl;
std::cout << boolalpha<<isMatch(s4, p4) << std::endl;
std::cout << boolalpha<<isMatch(s5, p5) << std::endl;
return 0;
}
//迭代
#include <iostream>
using namespace std;
bool isMatch(const char *s, const char *p) {
bool star = false;
const char *str, *ptr;
for (str = s, ptr = p; *str != '\0'; str++, ptr++) {
switch (*ptr) {
case '?':
break;
case '*':
star = true;
s = str, p = ptr;
while (*p == '*') p++; //skip continuous '*'
if (*p == '\0') return true;
str = s - 1;
ptr = p - 1;
break;
default:
if (*str != *ptr) {
// 如果前面没有'*',则匹配不成功
if (!star) return false;
s++;
str = s - 1;
ptr = p - 1;
}
}
}
while (*ptr == '*') ptr++;
return (*ptr == '\0');
}
int main(int argc, char const *argv[]) {
char *s1 = "aa", *p1 = "a";
char *s2 = "aa", *p2 = "*";
char *s3 = "aa", *p3 = "a*";
char *s4 = "ab", *p4 = "?*";
char *s5 = "aab",*p5 = "c*a*b";
std::cout << boolalpha<<isMatch(s1, p1) << std::endl;
std::cout << boolalpha<<isMatch(s2, p2) << std::endl;
std::cout << boolalpha<<isMatch(s3, p3) << std::endl;
std::cout << boolalpha<<isMatch(s4, p4) << std::endl;
std::cout << boolalpha<<isMatch(s5, p5) << std::endl;
return 0;
}
参考链接: