[LeetCode] 10. Regular Expression Matching 正则表达式匹配
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:
scould be empty and contains only lowercase lettersa-z.pcould be empty and contains only lowercase lettersa-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
类似题目:
参考资料:
https://leetcode.com/problems/regular-expression-matching/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 10. Regular Expression Matching 正则表达式匹配的更多相关文章
- [LeetCode]10. Regular Expression Matching正则表达式匹配
Given an input string (s) and a pattern (p), implement regular expression matching with support for ...
- [leetcode]10. Regular Expression Matching正则表达式的匹配
Given an input string (s) and a pattern (p), implement regular expression matching with support for ...
- 10. Regular Expression Matching正则表达式匹配
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
最近代码写的少了,而leetcode一直想做一个python,c/c++解题报告的专题,c/c++一直是我非常喜欢的,c语言编程练习的重要性体现在linux内核编程以及一些大公司算法上机的要求,pyt ...
- Leetcode 10. Regular Expression Matching(递归,dp)
10. Regular Expression Matching Hard Given an input string (s) and a pattern (p), implement regular ...
- leetcode 10. Regular Expression Matching 、44. Wildcard Matching
10. Regular Expression Matching https://www.cnblogs.com/grandyang/p/4461713.html class Solution { pu ...
- [LeetCode] Regular Expression Matching 正则表达式匹配
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- LeetCode (10): Regular Expression Matching [HARD]
https://leetcode.com/problems/regular-expression-matching/ [描述] Implement regular expression matchin ...
- 蜗牛慢慢爬 LeetCode 10. Regular Expression Matching [Difficulty: Hard]
题目 Implement regular expression matching with support for '.' and '*'. '.' Matches any single charac ...
随机推荐
- N!(hdu1042)
N! Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N! Input One N in one line, process ...
- tornado的使用-日志篇
tornado的使用-日志篇
- YY工具隐私政策
YY工具(以下简称“我们”)深知个人信息对您的重要性,并会尽全力保护您的个人信息安全可靠.我们致力于维持您对我们的信任,恪守以下原则,保护您的个人信息:权责一致原则.目的明确原则.选择同意原则.最少够 ...
- 在项目中使用Solr
web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=" ...
- 坑爹的京东E卡(京东E卡的正确使用方式)
前言 今年中秋公司发了200的京东E卡(下面简称礼品卡,京东简称jd)这让喜欢在jd自营购买商品的我很是开心, 兴致勃勃打开官网,当我选好商品准备结算时却发现礼品卡无法使用. 后 ...
- Redis set集合
Set操作.Set集合就是不允许重复的列表 (无序集合) sadd(name,values) # name对应的集合中添加元素 scard(name) # 获取name对应的集合中元素个数 sdiff ...
- http协议历史
HTTP 通常被译为超文本传输协议, 但这种译法并不严谨. 严谨的译名应该为“超文本转移协议”. 最初设想的基本理念是: 借助多文档之间相互关联形成的超文本( HyperText) , 连成可相互参阅 ...
- mpvue小程序开发之 实现一个弹幕评论
先上图 就是一个简单的弹幕发送功能 弹幕区的页面: <div class="content" v-show="doommData.length"> ...
- 英语JASPERITE碧玉Jasperite单词
碧玉为一种含矿物质较多的和田玉,其中氧化铁和粘土矿物等含量可达20%以上,不透.微透或半透,颜色多呈暗红色.绿色或杂色. 中文名碧玉 外文名Jasper,Jasperite 别 称玛钠斯玉 类 别按颜 ...
- 智能家居-1.基于esp8266的语音控制系统(开篇)
智能家居-1.基于esp8266的语音控制系统(开篇) 智能家居-2.基于esp8266的语音控制系统(硬件篇) 智能家居-3.基于esp8266的语音控制系统(软件篇) apache-apollo安 ...