題目描述
請實現一個函數用來匹配包括’.’和’‘的正則表達式。模式中的字符’.’表示任意一個字符,而’‘表示它前面的字符可以出現任意次(包含0次)。 在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串”aaa”與模式”a.a”和”ab*ac*a”匹配,但是與”aa.a”和”ab*a”均不匹配。
代碼
class Solution {
public:
bool match(char* str, char* pattern)
{
if (str == NULL || pattern == NULL) {
return false;
}
return matchCore(str, pattern);
}
bool matchCore(char* str, char* pattern)
{
if (*str == '\0' && *pattern == '\0') {
return true;
}
if (*str != '\0' && *pattern == '\0') {
return false;
}
if (*(pattern + 1) == '*') {
if (*pattern == *str || (*pattern == '.' && *str != '\0')) {
// move on the next state
return matchCore(str+1, pattern+1)
// state on the current state
|| matchCore(str+1, pattern)
// ignore a '*'
|| matchCore(str, pattern+2);
}
else{
// ignore a '*'
return matchCore(str, pattern+2);
}
}
if (*str == *pattern || (*pattern == '.' && *str != '\0')) {
return matchCore(str+1, pattern+1);
}
return false;
}
};