码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode -- Regular Expression Matching 【算法】

时间:2015-01-19 17:17:43      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:leetcode   正则表达式   

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* )。


LeetCode -- Regular Expression Matching 【算法】

标签:leetcode   正则表达式   

原文地址:http://blog.csdn.net/jdplus/article/details/42875011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!