Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

这道求正则表达式匹配的题和那道 Wildcard Matching 的题很类似,不同点在于*的意义不同,在之前那道题中,*表示可以代替任意个数的字符,而这道题中的*表示之前那个字符可以有0个,1个或是多个,就是说,字符串 a*b,可以表示b或是 aaab,即a的个数任意,这道题的难度要相对之前那一道大一些,分的情况的要复杂一些,需要用递归 Recursion 来解,大概思路如下:

- 若p为空,若s也为空,返回 true,反之返回 false。

- 若p的长度为1,若s长度也为1,且相同或是p为 '.' 则返回 true,反之返回 false。

- 若p的第二个字符不为*,若此时s为空返回 false,否则判断首字符是否匹配,且从各自的第二个字符开始调用递归函数匹配。

- 若p的第二个字符为*,进行下列循环,条件是若s不为空且首字符匹配(包括 p[0] 为点),调用递归函数匹配s和去掉前两个字符的p(这样做的原因是假设此时的星号的作用是让前面的字符出现0次,验证是否匹配),若匹配返回 true,否则s去掉首字母(因为此时首字母匹配了,我们可以去掉s的首字母,而p由于星号的作用,可以有任意个首字母,所以不需要去掉),继续进行循环。

- 返回调用递归函数匹配s和去掉前两个字符的p的结果(这么做的原因是处理星号无法匹配的内容,比如 s="ab", p="a*b",直接进入 while 循环后,我们发现 "ab" 和 "b" 不匹配,所以s变成 "b",那么此时跳出循环后,就到最后的 return 来比较 "b" 和 "b" 了,返回 true。再举个例子,比如 s="", p="a*",由于s为空,不会进入任何的 if 和 while,只能到最后的 return 来比较了,返回 true,正确)。

解法一:

class Solution {
public:
bool isMatch(string s, string p) {
if (p.empty()) return s.empty();
if (p.size() == ) {
return (s.size() == && (s[] == p[] || p[] == '.'));
}
if (p[] != '*') {
if (s.empty()) return false;
return (s[] == p[] || p[] == '.') && isMatch(s.substr(), p.substr());
}
while (!s.empty() && (s[] == p[] || p[] == '.')) {
if (isMatch(s, p.substr())) return true;
s = s.substr();
}
return isMatch(s, p.substr());
}
};

上面的方法可以写的更加简洁一些,但是整个思路还是一样的,先来判断p是否为空,若为空则根据s的为空的情况返回结果。当p的第二个字符为*号时,由于*号前面的字符的个数可以任意,可以为0,那么我们先用递归来调用为0的情况,就是直接把这两个字符去掉再比较,或者当s不为空,且第一个字符和p的第一个字符相同时,再对去掉首字符的s和p调用递归,注意p不能去掉首字符,因为*号前面的字符可以有无限个;如果第二个字符不为*号,那么就老老实实的比较第一个字符,然后对后面的字符串调用递归,参见代码如下:

解法二:

class Solution {
public:
bool isMatch(string s, string p) {
if (p.empty()) return s.empty();
if (p.size() > && p[] == '*') {
return isMatch(s, p.substr()) || (!s.empty() && (s[] == p[] || p[] == '.') && isMatch(s.substr(), p));
} else {
return !s.empty() && (s[] == p[] || p[] == '.') && isMatch(s.substr(), p.substr());
}
}
};

我们也可以用 DP 来解,定义一个二维的 DP 数组,其中 dp[i][j] 表示 s[0,i) 和 p[0,j) 是否 match,然后有下面三种情况(下面部分摘自这个帖子):

1.  P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
2.  P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;
3.  P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.

解法三:

class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size(), n = p.size();
vector<vector<bool>> dp(m + , vector<bool>(n + , false));
dp[][] = true;
for (int i = ; i <= m; ++i) {
for (int j = ; j <= n; ++j) {
if (j > && p[j - ] == '*') {
dp[i][j] = dp[i][j - ] || (i > && (s[i - ] == p[j - ] || p[j - ] == '.') && dp[i - ][j]);
} else {
dp[i][j] = i > && dp[i - ][j - ] && (s[i - ] == p[j - ] || p[j - ] == '.');
}
}
}
return dp[m][n];
}
};

GitHub 同步地址:

https://github.com/grandyang/leetcode/issues/10

类似题目:

Wildcard Matching

参考资料:

https://leetcode.com/problems/regular-expression-matching/

https://leetcode.com/problems/regular-expression-matching/discuss/5684/9-lines-16ms-c-dp-solutions-with-explanations

https://leetcode.com/problems/regular-expression-matching/discuss/5665/my-concise-recursive-and-dp-solutions-with-full-explanation-in-c

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Regular Expression Matching 正则表达式匹配的更多相关文章

  1. [LeetCode] 10. Regular Expression Matching 正则表达式匹配

    Given an input string (s) and a pattern (p), implement regular expression matching with support for  ...

  2. [LeetCode]10. Regular Expression Matching正则表达式匹配

    Given an input string (s) and a pattern (p), implement regular expression matching with support for ...

  3. 010 Regular Expression Matching 正则表达式匹配

    Implement regular expression matching with support for '.' and '*'.'.' Matches any single character. ...

  4. 10. Regular Expression Matching正则表达式匹配

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  5. [leetcode]10. Regular Expression Matching正则表达式的匹配

    Given an input string (s) and a pattern (p), implement regular expression matching with support for  ...

  6. [leetcode]Regular Expression Matching @ Python

    原题地址:https://oj.leetcode.com/problems/regular-expression-matching/ 题意: Implement regular expression ...

  7. LeetCode | Regular Expression Matching

    Regular Expression Matching Implement regular expression matching with support for '.' and '*'. '.' ...

  8. [LeetCode] Regular Expression Matching [6]

    称号: Implement regular expression matching with support for '.' and '*'. '.' Matches any single chara ...

  9. 10. Regular Expression Matching字符串.*匹配

    [抄题]: Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...

随机推荐

  1. JavaScript: 零基础轻松学闭包

    本文面向初学者,大神轻喷. 闭包是什么? 初学javascript的人,都会接触到一个东西叫做闭包,听起来感觉很高大上的.网上也有各种五花八门的解释,其实我个人感觉,没必要用太理论化的观念来看待闭包. ...

  2. Basic Tutorials of Redis(5) - Sorted Set

    The last post is mainly about the unsorted set,in this post I will show you the sorted set playing a ...

  3. 使用C#代码生成一个随机的UUID

    在日常开发中常见于生成主键的ID,比较规范好用,详细代码如下(写注释是个好习惯): using System;using System.Collections.Generic;using System ...

  4. 在DevExpress程序中使用条形码二维码控件,以及进行报表打印处理

    在很多业务系统里面,越来越多涉及到条形码.二维码的应用了,不管在Web界面还是WInform界面都需要处理很多物料相关的操作,甚至很多企业为了减少录入错误操作,为每个设备进行条形码.二维码的标签,直接 ...

  5. Warning: mysql_connect(): No such file or directory 解决方案总结(操作系统: Mac)

    说明: 本文主要内容参考: Mac下PHP连接MySQL报错"No such file or directory"的解决办法, 并进行个人补充 1. 运行环境: Mac OS X 10.11.4 (M ...

  6. 《连载 | 物联网框架ServerSuperIO教程》- 9. 协议过滤器,解决一包多发、粘包、冗余数据

    1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...

  7. GJM : Unity3D HIAR -【 快速入门 】 二、搭建开发环境

    感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...

  8. javascript 表单

    在HTML中,表单是由<form>元素来组成的.在js中,表单对应的则是HTMLFormElement类型.它和其他HTML元素一样具有相同的默认属性.下面是HTMLFormElement ...

  9. css3 linear-gradient实现购物车地址选择信封效果

    对于css3的渐变前端的童鞋一定不陌生,在一些电商网站会为了美化将地址选择做成信封样式(个人感觉很稀饭~),看了一下它的实现方式,大多数是以图片的形式,持着优化的心态尝试着用css3 linear-g ...

  10. OC多态

    要点: 1.多种形态,引用的多种形态对于一个引用变量,可以指向任何类的对象.对于一个父类的引用(类与类之间有一种继承关系),可以指向子类,也可以指向本类,指向的类型不同.当通过此引用向对象发送消息,调 ...