剑指 Offer 19. 正则表达式匹配

题目描述

请实现一个函数用来匹配包含'. ''*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a""ab*ac*a"匹配,但与"aa.a""ab*a"均不匹配。

示例1:

输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。

示例2:

输入:
s = "aa"
p = "a*"
输出: true
解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。

示例3:

输入:
s = "ab"
p = ".*"
输出: true
解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。

示例4:

输入:
s = "aab"
p = "c*a*b"
输出: true
解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。

示例5:

输入:
s = "mississippi"
p = "mis*is*p*."
输出: false
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母以及字符 . 和 *,无连续的 '*'。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof

代码实现

class Solution {
public:
	bool isMatch(string s, string p) {
		vector<vector<int>> dpmt(s.length() + 1, vector<int>(p.length() + 1, -1));
		return dp(0, 0, s, p, dpmt);
	}
	bool dp(int i, int j, string s, string p, vector<vector<int>>& dpmt) {
		if (dpmt[i][j] != -1)
			return dpmt[i][j];
		bool result;
		if (j == p.length()) {
			result = (i == s.length());
			return result;
		}
		bool first_match = samechar(s[i], p[j]);
		if (j + 1 < p.length() && p[j + 1] == '*') {
			result = dp(i, j + 2, s, p, dpmt) || (first_match && dp(i + 1, j, s, p, dpmt));
		}
		else {
			result = first_match && dp(i + 1, j + 1, s, p, dpmt);
		}
		dpmt[i][j] = result ? 1 : 0;
		return result;
	}
	bool samechar(char& sc, char& pc) {
		if (sc < 'a' || sc > 'z')
			return false;
		if (pc == '.')
			return true;
		if (sc == pc)
			return true;
		return false;
	}
};
原文地址:https://www.cnblogs.com/xqmeng/p/13587423.html