1,题目要求
Given an input string (s) and a pattern §, 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
给定输入字符串和模式(p),实现与支持’。‘的正则表达式匹配。 和’*’。
‘.’ 匹配任何单个字符。
'*'匹配前面元素的零个或多个。
匹配应覆盖整个输入字符串(不是部分)。
注意:
- s可以为空,只包含小写字母a-z。
- p可以为空,只包含小写字母a-z和字符。 要么 *。
2,题目思路
对于这道题,是实现一个正则表达式的匹配。
对于正则式的匹配,主要有两个字符:
- ‘.’:可以匹配任何字符。
- ’ * ':匹配前面元素的零个或多个。
对于这个问题上,首先
1,如果s为空而p是"*",则返回true。
2,如果s为空而且p是空,则返回true。
3,如果s非空而p为空,则返回false。
4,没有连续出现 * 的情况。
其次,在对问题的解决上,我们使用动态规划,设置dp[i][j]为s[0…i]是否等于p[0…j]
1,如果p[j] == s[I],则dp[i][j] = dp[i-1][j-1]
2,如果p[j] == ‘.’,则dp[i][j] = dp[i-1][j-1]
3,如果p[j] == ‘#’:
- 如果p[j-1] != s[i]:则dp[i][j] = dp[i][j-2](此时, a*作为空)
- 如果p[j-1] == s[i] 或者 p[i-1] == ‘.’,此时:
dp[i][j] = dp[i-1][j](此时,a *作为多个a)
或者 dp[i][j] = dp[i][j-1](此时,a *作为一个a)
或者 dp[i][j] = dp[i][j-2](此时,a *作为空)
3,代码实现
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size(), n = p.size();
//对合法输入进行检查
if(m == 0 && (p[0] == '*' || n == 0))
return true;
if(m != 0 && n == 0)
return false;
vector<vector<bool>> dp (m+1, vector<bool> (n+1, false));
dp[0][0] = true;
//用于解决s = "a",p = "b*a"的情况
for(int j = 0;j<n;j++)
if(p[j] == '*' && dp[0][j-1])
dp[0][j+1] = true;
//.:可代替任何字符
//*:表示对前面的字符重复0次或者多次
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++){
if(p[j] == '.')
dp[i+1][j+1] = dp[i][j];
if(p[j] == s[i])
dp[i+1][j+1] = dp[i][j];
if(p[j] == '*'){
if(p[j-1]!=s[i] && p[j-1]!='.')
dp[i+1][j+1] = dp[i+1][j-1];
else
dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
}
}
return dp[m][n];
}
};