标签:
题目:
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
思路:
这题目一开始看起来给人一种不知道从何入手的感觉,总觉得要考虑的情况太多了。但其实仔细一想, ‘.‘ 符号只需要继续下移一个, ‘*‘ 才是需要考虑的一个点。用递归的方法来扫描字符串,若第二个字符不为 ‘*‘ ,则直接匹配当前字符,递归判断除当前字符后的字符,若第二个字符为 ‘*‘ ,一是当前字符和 ‘*‘ 所组合匹配的结果为0个,则 p 串后移两个位与 s 串匹配,否则一直匹配到当前字符不相同时, p 串后移两位继续匹配。匹配成功的条件是
( (*s != ‘\0‘ && *p == ‘.‘) || *s == *p )
代码:
1 bool isMatch(const char *s, const char *p) 2 { 3 if (s == NULL || p == NULL) return false; 4 if (*p == ‘\0‘) return *s == ‘\0‘; 5 6 if (*(p + 1) == ‘*‘) 7 { 8 while ((*s != ‘\0‘ && *p == ‘.‘) || *s == *p) 9 { 10 if (isMatch(s, p + 2)) return true; 11 ++s; 12 } 13 14 return isMatch(s, p + 2); 15 } 16 else if ((*s != ‘\0‘ && *p == ‘.‘) || *s == *p) 17 { 18 return isMatch(s + 1, p + 1); 19 } 20 21 return false; 22 }
标签:
原文地址:http://www.cnblogs.com/YaolongLin/p/4856122.html