您的位置:首页 > 其它

LeetCode | Regular Expression Matching

2014-05-07 15:00 417 查看

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 == 0 && pn == 0) return true;
if (pn == 0) return false;

if (*(p + 1) != '\0') {
if (*(p + 1) == '*') {
if (*p == '.') { // .*
int n = 0;
while (n <= sn) {
if (recursive(s + n, sn - n, p + 2, pn - 2)) return true;
n++;
}
} else { // a*
int n = 0;
while (n <= sn && *(s + n) == *p) {
if (recursive(s + n, sn - n, p + 2, pn - 2)) return true;
n++;
}
if (recursive(s + n, sn - n, p + 2, pn - 2)) return true;
}
} else {
if (*p != '.' && *s != *p) return false;
if (recursive(s + 1, sn - 1, p + 1, pn - 1)) return true;
}
} else {
if (*p != '.' && *s != *p) return false;
if (recursive(s + 1, sn - 1, p + 1, pn - 1)) 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 + 1) != '*') {
return ((*s == *p || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1));
}

// match a*, .*
while ((*s == *p || (*p == '.' && *s != '\0'))) {
if (isMatch(s++, p + 2)) return true;
}

// ignore a*, *p != '.' && *s != *p
return isMatch(s, p + 2);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: