LeetCode.010 Regular Expression Matching

本文介绍了如何实现正则表达式的匹配功能,支持点匹配任意单个字符和星号匹配前一个字符的零次或多次出现。通过递归方法简化代码,确保整个输入字符串被正确匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意
带通配符带字符串匹配。
.        匹配任意的单个字符
*        匹配前一个字符的零个或者多个出现
思路
借鉴代码之美中的解决方案,利用递归的方法,代码简洁,易懂。
 1 //摘自《代码之美》
 2 // 字符     含义
 3 // .        匹配任意的单个字符
 4 // ^        匹配输入字符串的开头
 5 // $        匹配输入字符串的结尾
 6 // *        匹配前一个字符的零个或者多个出现
 7 #include <stdio.h>
 8 int matchhere(char *regexp, char *text);
 9 
10 int matchstar(int c, char *regexp, char *text) {// matchstar: search for c*regexp at beginning of text
11    do {// a * matches zero or more instances
12        if (matchhere(regexp, text)) return 1;
13    } while (*text != '\0' && (*text++ == c || c == '.'));
14    return 0;
15 }
16 int matchhere(char *regexp, char *text) {// matchhere: search for regexp at beginning of text
17    if (regexp[0] == '\0') return 1;
18    if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text);
19    if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0';
20    if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1);
21    return 0;
22 }
23 
24 int match(char *regexp, char *text) {// match: search for regexp anywhere in text
25     if (regexp[0] == '^') return matchhere(regexp+1, text);
26     do {// must look even if string is empty
27         if (matchhere(regexp, text)) return 1;
28     } while (*text++ != '\0');
29     return 0;
30 }
View Code

下面是自己的关于此题的代码。

 1 bool isMatch(char* s, char* p);
 2 bool matchstar(int c,char *s,char *p)  
 3 {
 4     do {// a * matches zero or more instances
 5         if (isMatch(s, p)) return 1;
 6     } while (*s != '\0' && (*s++ == c || c == '.'));
 7     return 0;
 8 }
 9 bool isMatch(char* s, char* p) {
10     if(p[0]=='\0' && s[0]=='\0') return 1;
11     if(p[1]=='*') return matchstar(p[0], s,p+2);
12     if(*s!='\0' && (p[0]=='.' || *s==p[0])) return isMatch(s+1,p+1);
13     return 0;
14     
15 }

 

转载于:https://www.cnblogs.com/madking/p/4658538.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值