题解 | #正则表达式匹配#
正则表达式匹配
https://www.nowcoder.com/practice/28970c15befb4ff3a264189087b99ad4
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @param pattern string字符串
* @return bool布尔型
*/
bool match(string str, string pattern) {
// write code here
vector<vector<bool> > dp(str.length() + 1, vector<bool>(pattern.length() + 1,
false));
dp[0][0] = true;
for (int j = 0; j < pattern.length() + 1; j++) {
if (pattern[j] == '*' && dp[0][j - 1] == true) {
dp[0][j + 1] = true;
} else if (pattern[j] == '.') {
dp[0][j + 1] = true;
}
}
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < pattern.length(); j++) {
if (str[i] == pattern[j]) {
dp[i + 1][j + 1] = dp[i][j];
} else if (pattern[j] == '*') {
if (dp[i + 1][j - 1] == true || ((str[i] == pattern[j - 1]||pattern[j-1]=='.') &&
dp[i][j + 1] == true)) dp[i + 1][j + 1] = true;
} else if (pattern[j] == '.') {
dp[i + 1][j + 1] = dp[i][j];
}
}
}
return dp[str.length()][pattern.length()];
}
};
