LeetCode | Regular Expression Matching

时间:2024-06-15 00:04:14

Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

思路是分别处理a*、.*、.、a的情况。

三周前写的lengthy code如下:

 class Solution {
public:
bool isMatch(const char *s, const char *p) {
int sn = strlen(s);
int pn = strlen(p);
return recursive(s, sn, p, pn);
} bool recursive(const char* s, int sn, const char* p, int pn) {
if (sn == && pn == ) return true;
if (pn == ) return false; if (*(p + ) != '\0') {
if (*(p + ) == '*') {
if (*p == '.') { // .*
int n = ;
while (n <= sn) {
if (recursive(s + n, sn - n, p + , pn - )) return true;
n++;
}
} else { // a*
int n = ;
while (n <= sn && *(s + n) == *p) {
if (recursive(s + n, sn - n, p + , pn - )) return true;
n++;
}
if (recursive(s + n, sn - n, p + , pn - )) return true;
}
} else {
if (*p != '.' && *s != *p) return false;
if (recursive(s + , sn - , p + , pn - )) return true;
}
} else {
if (*p != '.' && *s != *p) return false;
if (recursive(s + , sn - , p + , pn - )) return true;
}
}
};

今天看了Leetcode上1337的代码真是羞愧啊。http://leetcode.com/2011/09/regular-expression-matching.html

重写了一遍。思路还是一样。

 class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (*p == '\0') return (*s == '\0');
// match single '\0', '.', 'a'...
if (*(p + ) != '*') {
return ((*s == *p || (*p == '.' && *s != '\0')) && isMatch(s + , p + ));
} // match a*, .*
while ((*s == *p || (*p == '.' && *s != '\0'))) {
if (isMatch(s++, p + )) return true;
} // ignore a*, *p != '.' && *s != *p
return isMatch(s, p + );
}
};