'?'可匹配任意单个字符.
'*'可匹配任意字符,包括空.
例如:
s: abc p: a?c ->匹配成功
s: abc p: a* ->匹配成功
实现基本逻辑是从左至右依次匹配,匹配到'*'时,更新cache,将*依次扩展字符进行匹配。
#include<iostream>
#include <fstream>
#include<string>
static bool isMatch(const char *sStr, const char *pStr);
int main()
{
char source[] = "abcd";
char part[] = "a**d";
bool match = isMatch(source, part);
std::cout << match<< std::endl;
system("pause");
}
static bool isMatch
(
const char *sStr, /* I: Source string */
const char *pStr /* I: pattern string */
)
/*
DESCRIPTION:
Check whether the pattern string matches the source string.
RETURN:
Return 1 if match, else 0.
*/
{
int cache[2] = { -1, -1 };
int sPos = 0, pPos = 0;
while (sPos < strlen(sStr))
{
if (pPos < strlen(pStr) && (pStr[pPos] == sStr[sPos]) ||
pStr[pPos] == '?' || pStr[pPos] == '*')
{
if (pStr[pPos] == '*')
{
cache[0] = pPos;
cache[1] = sPos;
}
else
{
sPos++;
}
pPos++;
}
else if (cache[0] != -1)
{
pPos = cache[0] + 1;
sPos = cache[1] + 1;
cache[1]++;
}
else
return false;
}
/* such as "a", "a*" condition */
while (pPos < strlen(pStr) && pStr[pPos] == '*')
pPos++;
return (pPos == strlen(pStr));
}