[LeetCode][Facebook面试题] 通配符匹配和正则表达式匹配,题 Wildcard Matching 开篇 正则表达式匹配

通常的匹配分为两类,一种是正则表达式匹配,pattern包含一些关键字,比如'*'的用法是紧跟在pattern的某个字符后,表示这个字符可以出现任意多次(包括0次)。

另一种是通配符匹配,我们在操作系统里搜索文件的时候,用的就是这种匹配。比如 "*.pdf",'*'在这里就不再代表次数,而是通配符,可以匹配任意长度的任意字符组成的串。所以"*.pdf"表示寻找所有的pdf文件。

在算法题中,往往也会有类似的模拟匹配题,当然考虑到当场实现的时间,会减少通配符数量或者正则表达式关键字的数量,只留那么几个,即便如此,这类题目也是属于比较难的题目了==。 

正则表达式匹配

例题如下:

Regular Expression Matching

http://basicalgos.blogspot.com/2012/03/10-regular-expression-matching.html

'.' 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

 

这道题是面Facebook时遇到的一道题。

要处理的关键字有两个'*', '.' ,第二个比较好办,第一个比较麻烦,

因为'*'可以表示任意数量,因此当*(p+1) == '*'时,我们可以掠过'*'之前的字符,直接++p,或者如果*s == *(p-1)或*(p-1) == '.',我们可以跳过任意个这样的s。因此,'*'的处理被跳过多少个s划分成了多个子问题,我用递归函数来处理这些子问题。当时的代码还没有这么简洁,这是我修改后的代码:

bool isMatch(char *s, char *p){
    if(*s == '