zoukankan      html  css  js  c++  java
  • Leetcode 10. Regular Expression Matching

     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];
    	}
    };
    

    参考思路:

    Subscribe 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,要求两个串都匹配完,现在要进行状态转移

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

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

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

  • 相关阅读:
    基于WINCE嵌入式系统的FM1702的读写器(2)
    WINCE 按键驱动编写
    WinCE内存调整
    USB模块
    网络模块
    wince6.0下ov9650的图像保存
    Windows CE内存泄漏
    MPEG4解码函数
    centos 7 gitlab安装 李刚
    docker 17.12.0ce 空间大小和容器大小限制修改 李刚
  • 原文地址:https://www.cnblogs.com/bitch1319453/p/6601037.html
Copyright © 2011-2022 走看看