LeetCode题解——Regular Expression Matching

题目

正则表达式的匹配,'.'能匹配任何一个字符,'*'之前必须有一个字符,两个结合起来表示之前那个字符出现0到无穷次。

 

解法

一定要注意'*'必须结合前面的字符一起使用。

 

代码

 1 class Solution {  2 public:  3     bool isMatch(const char *s, const char *p) {  4         if(s == NULL || p == NULL)  5             return false;  6         if(*p == '\0')  7             return *s == '\0';  8             

 9         if(*(p+1) != '*')  //如果模式串的下一位不是'*',则判断当前字符 10             if(*s == *p || (*p == '.' && *s != '\0'))  //相等,或模式串碰到万能的'.',则继续往后匹配 11                 return isMatch(s+1, p+1); 12             else

13                 return false; 14         

15         while(*s == *p || (*p == '.' && *s != '\0'))  //模式串的下一位是'*',如果当前字符相同或模式串是万能的'.' 16  { 17             if(isMatch(s, p+2))  //模式串的'*'表示出现0次时的结果 18                 return true; 19             ++s;  //s前进1,表示'*'多匹配了一个 20  } 21         

22         return isMatch(s, p+2);  //'*'不匹配,跳过这个模式 23  } 24 };

 

你可能感兴趣的:(LeetCode题解——Regular Expression Matching)