标签:style blog io ar strong for art div cti
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
思路: 这题 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
标签:style blog io ar strong for art div cti
原文地址:http://www.cnblogs.com/liyangguang1988/p/3961261.html