1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Regular Expression Matching

Posted on 2013-10-15 09:47  1957  阅读(1017)  评论(1编辑  收藏  举报

正则表达式的匹配,一看吓尿了。

写个正则引擎还是挺麻烦的。。

不过仔细一看,原来是精简过的,只有. *这两种(正则好像也就这两种)

主要就是*,匹配0到多个。。。

那直接用递归吧。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Note: The Solution object is instantiated only once and is reused by each test case.    
       if(*p == '\0') return *s == '\0';
       if(*(p + 1) != '*'){
           return (*s == *p || (*p == '.' && *s != '\0')) && isMatch(s+1 , p+1);
       }else{
           while(*p == *s || (*p == '.' && *s != '\0')){
               if(isMatch(s , p+2)) return true; //match 1,2,3,4....n
               s++;
           }
           return isMatch(s , p+2); //match 0
       }
    }
};