题目原文:
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).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
题目分析:
判断输入的源字符串和目标字符串中的正则表达式是否匹配。
注意,不可使用贪心进行匹配,因为贪心很可能会过多的匹配字符,例如aaaab和a*ab进行匹配判断时,a*会将所有a匹配完,导致判断两个字符串不相等。
使用动态规划进行后续匹配,选择一种后续可以匹配完的匹配方式。(若都无法匹配完成则失败)
代码示例:
//正则表达式的匹配情况,不能一味的进行贪心匹配,需要考虑后续模式的匹配情况
//使用动态规划算法进行处理,与求最长公共子序列思想相似
//遇到一个匹配模式后,可以有匹配该模式和不匹配该模式两种分支,选择可以完成字符正则匹配的分支
#include <iostream>
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
//匹配完成,返回true
if (s.length() == 0 || p.length()==0)
{
if (s.length() == p.length())
{
return true;
}
else if (p.length()>1 && p[1] == '*')
{
return isMatch(s,p.substr(2,p.length())); //匹配0个,跳过该模式
}
else
return false;
}
if (s[0] == p[0] || p[0] == '.') //首个字符匹配
{
/*if (s.length() == p.length()&& s.length() ==1)
{
return true;
}*/
if (p.length()>1 && p[1] == '*') //多重匹配,0个或多个
{
if (isMatch(s.substr(1, s.length()),p)) //匹配一个,继续往下匹配
{
return true;
}
else
return isMatch(s,p.substr(2,p.length())); //匹配0个,跳过该模式
}
else
return isMatch(s.substr(1, s.length()),p.substr(1,p.length())); //单个匹配
}
else if (p.length()>1 && p[1] == '*') //首字母不匹配,跳过该模式
{
return isMatch(s,p.substr(2,p.length()));
}
else //无法匹配
return false;
}
};