首页 > 代码库 > 66. Regular Expression Matching

66. Regular Expression Matching

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
思路: 这题 ugly 之处,在于 ‘*‘ 给的很不明朗, 其实‘c*‘, 表示 ‘*‘ 可以代表 ‘ccc...cc‘。
对 ‘*‘ 的理解,若出现 p中出现 ‘*‘, 则要比较用 s 和 p 中 ‘*‘ 之前的那个元素比较,从左往右找出 s 中第一个与 p 之前的元素不同的元素。
(若全相同,例如, 之前那个元素为 ‘.‘, 则 ‘.*‘ (表示‘.......^....‘)可以匹配任何 s 串)。
//垃圾题!rubbish question!class Solution {public:    bool isMatch(const char *s, const char *p) {           if (s == NULL || p == NULL) return false;        if (*p == ‘\0‘) return *s == ‘\0‘;        // ".*" matches "", so we can‘t check (*s == ‘\0‘) here.        if (*(p + 1) == ‘*‘){        // Here *p != ‘\0‘, so this condition equals with        // (*s != ‘\0‘ && (*p == ‘.‘ || *s == *p)).            while ((*s != ‘\0‘ && *p == ‘.‘) || *s == *p){                if (isMatch(s, p + 2)) return true;                ++s;            }            return isMatch(s, p + 2);        }        else if ((*s != ‘\0‘ && *p == ‘.‘) || *s == *p){            return isMatch(s + 1, p + 1);        }    return false;    }};

 












66. Regular Expression Matching