加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

LeetCode -- Regular Expression Matching 【算法】

发布时间:2020-12-14 01:27:13 所属栏目:百科 来源:网络整理
导读: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 prototy

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
题目要求实现一个可以支持'.'和'*'的正则表示,代码如下:



依题意,我们根据字符串P的下一个字符是否是'*'来分开讨论(见代码第7行)。如果是,那么必须在两字符串当前位置进行比较;否则,让字符串P的当前位置与字符串S的当前及后面各位比较直至不匹配,并开始下一轮的比较。为了避免字符串P的'*'匹配过多的项,还要对S从当前位置开始的子串和P从当前位置后面两位开始的子串进行匹配(样例:a ab* )。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读