• Regular Expression Matching


    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

     

    思路:因’*’可以匹配0到多个字符,所以,本题的难点就在于如何处理’*’

    首先,s[i]p[j]是否匹配,就看是否满足条件:s[i] = p[j],或者p[j]=’.’

    然后先看最简单的情况,如果p[j+1]不是’*’的话,就看s[i]p[j]是否匹配,如果匹配,则整个模式匹配与否取决于s[i+1..]p[j+1..]匹配与否。若不匹配,则整个模式就是不匹配的。

    如果p[j+1]’*’,并且s[i]p[j]匹配,则需要查看’*’匹配0到多个的情况,匹配0,就是匹配s[i..]p[j+2..],匹配1,就是匹配s[i+1..]p[j+2..],以此类推。

    如果p[j+1]’*’,并且s[i]p[j]不匹配,则需要将s[i..]p[j+2..]进行匹配。代码如下:

    char isMatch(char* s, char* p) 
    {  	 
    	if (*p == 0) return *s == 0;  
    	
    	if (*(p+1) != '*')	
    	{  
    		if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s+1, p+1);  
    		else return 0;	
    	}  
    	else  
    	{  
    		// *s == *p  
    		while (*s != 0 && (*s == *p || *p == '.'))	
    		{  
    			if (isMatch(s, p+2)) return 1;  
    			s++;  
    		}  
    		return (isMatch(s, p+2));  
    	}  
    } 
    

      


  • 相关阅读:
    网址
    123
    工具安装
    博客专栏-计算机网络
    JQuery(1)
    HTML常用标签
    Spring的线程池技术:ThreadPoolTaskExecutor
    Error:java: 程序包lombok不存在- IDEA+maven+lombok
    Andriod Studio中新创建的xml布局文件无法在R.layout中调用
    SAST : Single-Shot Arbitrarily-Shaped Text Detector论文阅读笔记
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247154.html
Copyright © 2020-2023  润新知