博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 10. Regular Expression Matching
阅读量:7072 次
发布时间:2019-06-28

本文共 1411 字,大约阅读时间需要 4 分钟。

class Solution {public:	bool judge(char a,char b)	{		if(a==b||b=='.')			return true;		return false;	}    bool isMatch(string s, string p) {        int n=s.length();        int m=p.length();        int idx=0;        bool dp[1008][1008];        memset(dp,false,sizeof(dp));        dp[0][0]=true;        for(int i=0;i<=n;i++)        	for(int j=1;j<=m;j++)        	{        		if(p[j-1]=='*'&&j-2>=0)        		{        			if(dp[i][j-2])        				dp[i][j]=true;        			if(i>0&&dp[i-1][j]&&judge(s[i-1],p[j-2]))        				dp[i][j]=true;				}				else				{					if(i>0&&dp[i-1][j-1]&&judge(s[i-1],p[j-1]))						dp[i][j]=true;				}			}		return dp[n][m];	}};

参考思路:

 to see which companies asked this question

 

This problem has a typical solution using Dynamic Programming. We define the state P[i][j] to be true if s[0..i) matches p[0..j)and false otherwise. Then the state equations are:

  1. P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
  2. P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;
  3. P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.

这样的动态规划可以这样理解:

用正则表达式p匹配s,要求两个串都匹配完,现在要进行状态转移

如果是字符或'.',显然只要按照正常的匹配方式即可

’*‘和它之前的字符却有多种匹配方式:一个也不匹配,或者匹配它所有能匹配的字符。这时只要之前的状态是可行的,那么当前状态就是可行的

总的来说是个比较难想的分类讨论。当然还有递归的方式解决这个问题啦

转载于:https://www.cnblogs.com/bitch1319453/p/6601037.html

你可能感兴趣的文章
Notification启动Activity, 恢复任务栈
查看>>
使用Python进行并发编程
查看>>
自动机器学习简述(AutoML)
查看>>
iPhone X适配
查看>>
虚拟化笔记
查看>>
[vim]-vim基础
查看>>
JAVA 8入门(一)Lambda表达式
查看>>
resin集成eclipse开发
查看>>
将Excel文件中的数据导入到mysql【Excel中拼sql】
查看>>
H5移动端知识点
查看>>
【js与jquery】网站更换皮肤功能
查看>>
Ubuntu ssh连接root验证错误
查看>>
汉字转化为拼音
查看>>
基于TP的SenCMS目录结构
查看>>
jquery 验证提交
查看>>
Yaf框架的扩展-mvc-路由配置-模版视图smarty加载
查看>>
单行文本溢出and多行文本溢出...以省略号展现
查看>>
MYSQL语句
查看>>
Android WebView 详解(持续更新)
查看>>
ElasticSearch动态添加节点及相关配置项
查看>>