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 lettersa-z
.p
could 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 preceding 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". (C可以重复0次,A可以重复1次。因此,它匹配“aab”)
Example 5:
Input: s = "mississippi" p = "mis*is*p*." Output: false
题目就不过多解释,主要就是第四个例子,c*可以匹配字符串中0个或多个字符,所以例4是正确的,做这个题目先分析一下怎么去写这个程序,因为那个c*之类的匹配很不好写,用递归就显得简单,所以我用递归写的,下面是分析
1.先判断p,s是否为空,p匹配s,分成四种情况p空 s空,p空 s非空,s空 p非空(这样子的化p只能是.*.*这样子,所以写断用来判断这种情况),剩下就来写 s非空 p非空,这种情况分为两种情况考率,第一种,p的前面两字符串是 一个字母一个*这样子,第二种就是两个字母相同或者p为.,这两种情况都可以截取字符串进行递归判断子字符串是否匹配就可以判断出来p是否匹配s,具体代码如下
class Solution {
public:
bool isMatch(string s, string p) {
if (!p.length() && !s.length())return true;
if (!p.length() && s.length() > 0)return false;
if (!s.length()) //s为空,p只能为.*.*.*
{
if (p.length() % 2 == 1)return false;
int i = 1;
while(i<p.length()&&p[i]=='*')
{
i += 2;
}
if (i == p.length() + 1)return true;
else return false;
}
//p[i]==* 用p+2 匹配s+0,s+1,s+2,s+3 成功返回true 失败返回false
int i = -1;
if (p.length() >= 2 && p[1] == '*') {
do
{
// 当++i为len+1时截取字符串才会越界报错,但是++i为len时截取的子串为空就已经返回结果了,所以永远没有机会截取len+1
if (isMatch(s.substr(++i), p.substr(2)))
return true;
else if (i == s.length())return false;
} while ((s[i] == p[0]) || p[0] == '.');
return false;
}
else {
if (s[0] == p[0] || p[0] == '.')
return isMatch(s.substr(1), p.substr(1));
else
{
return false;
}
}
}
};