题目描述
- 请实现一个函数用来匹配包含'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但与"aa.a"及"ab*a"均不匹配。
算法分析
- 当模式中的第二个字符不是“*”时:
2. 如果字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
- 而当模式中的第二个字符是“*”时:
1. 模式后移2字符,相当于x*被忽略;
2. 字符串后移1字符,模式后移2字符;
3. 字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位。
提交代码:
class Solution {
public:
bool match(char* str, char* pattern)
{
if (!str || !pattern)
return false;
return matchCore(str, pattern);
}
bool matchCore(char* str, char* pattern)
{
if (*pattern == '\0' && *str == '\0')
return true;
if (*pattern == '\0' && *str != '\0')
return false;
if (*(pattern + 1) == '*')
{
// 若存在'*'匹配
if (*str == *pattern || (*pattern == '.' && *str != '\0'))
// *无匹配字符
return matchCore(str, pattern + 2)
// *匹配单个字符
|| matchCore(str + 1, pattern + 2)
// 继续*匹配
|| matchCore(str + 1, pattern);
else
// 若'*'匹配0个
return matchCore(str, pattern + 2);
}
if(*str == *pattern || (*pattern == '.' && *str != '\0'))
return matchCore(str + 1, pattern + 1);
return false;
}
};
测试代码:
// ====================测试代码====================
void Test(char* testName, char* string, char* pattern, bool expected)
{
if (testName != nullptr)
printf("%s begins: ", testName);
Solution s;
if (s.match(string, pattern) == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
Test("Test01", "", "", true);
Test("Test02", "", ".*", true);
Test("Test03", "", ".", false);
Test("Test04", "", "c*", true);
Test("Test05", "a", ".*", true);
Test("Test06", "a", "a.", false);
Test("Test07", "a", "", false);
Test("Test08", "a", ".", true);
Test("Test09", "a", "ab*", true);
Test("Test10", "a", "ab*a", false);
Test("Test11", "aa", "aa", true);
Test("Test12", "aa", "a*", true);
Test("Test13", "aa", ".*", true);
Test("Test14", "aa", ".", false);
Test("Test15", "ab", ".*", true);
Test("Test16", "ab", ".*", true);
Test("Test17", "aaa", "aa*", true);
Test("Test18", "aaa", "aa.a", false);
Test("Test19", "aaa", "a.a", true);
Test("Test20", "aaa", ".a", false);
Test("Test21", "aaa", "a*a", true);
Test("Test22", "aaa", "ab*a", false);
Test("Test23", "aaa", "ab*ac*a", true);
Test("Test24", "aaa", "ab*a*c*a", true);
Test("Test25", "aaa", ".*", true);
Test("Test26", "aab", "c*a*b", true);
Test("Test27", "aaca", "ab*a*c*a", true);
Test("Test28", "aaba", "ab*a*c*a", false);
Test("Test29", "bbbba", ".*a*a", true);
Test("Test30", "bcbbabab", ".*a*a", false);
return 0;
}