实现正则表达式的.和*

失败的经历:

1.想用循环来实现,发现基本不可能啊。

2.想用NFA->DFA实现,还是算了吧,又不是真的实现正则表达式引擎。


建议先自己实现,我这边有testCase可以测试,一边调试一边找错,会发现最后的实现很不错。啥都不说了,上代码。

本题目我最招是从coding_interview上看到的,这本书也很是不错。




// How do you implement a function to match regular expressions with ‘.’ and ‘*’ in patterns? The
// character ‘.’ in a pattern matches a single character, and ‘*’ matches zero or any number of characters preceding
// it. Matching means that a string fully matches the pattern where all characters in a string match the whole pattern.
// For example, the string “aaa” matches the pattern “a.a” and the pattern “ab*ac*a”. However, it does not match
// the pattern “aa.a” nor “ab*a”.


#include <stdio.h>
#include <assert.h>


bool match(char* myString, char* pattern){


if(myString == NULL || pattern == NULL){
return false;
}


if(*myString != '\0' && *pattern != '\0'){
if(pattern[1] == '*'){
// this recursive can't be replaced by loop, they work together and coordinate complicatedly
if(*myString == *pattern || *pattern == '.'){
return match(myString, pattern + 2) //skip * 
|| match(myString + 1, pattern + 2) //eat a ch and skip *
|| match(myString + 1, pattern) //stay at current parrtern
;
}
else{
return match(myString, pattern + 2); //skip * 
}
}
else{
if(*myString == *pattern || *pattern == '.'){
return match(myString + 1, pattern + 1);
}
else{
return false;
}
 
}
}//for
if(*myString != '\0' || *pattern != '\0'){
return false;
}
return true;
}


//test case 0. NULL , a.a
//test case 0. NULL , NULL
//test case 0. aaa , NULL
//test case 1. aaa , a.a
//test case 1. aaa , a.*a
//test case 2. aaa , ab*ac*a
//test case 3. aaa , aa.a
//test case 4. aaa , ab*a
//test case 4. aaa , .
//test case 4. aaa , * //invalid
//test case 4. aaa , .*
//test case 4. aaa , a.*
//test case 4. aaa , a*


void testCase0(){

bool 
result = match(NULL, "a.a");
assert(!result);
result = match(NULL, NULL);
assert(!result);
result = match("aaa", NULL);
assert(!result);
result = match("aaa", "a.a");
assert(result);
result = match("aaa", "a.*a");
assert(result);
result = match("aaa", "ab*ac*a");
assert(result);
result = match("aaa", "aa.a");
assert(!result);
result = match("aaa", "ab*a");
assert(!result);
result = match("aaa", ".");
assert(!result);
result = match("aaa", "*");
assert(!result);
result = match("aaa", ".*");
assert(result);
result = match("aaa", "a.*");
assert(result);
result = match("aaa", "a*");
assert(result);
}
int main(){
testCase0();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值