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

  


 

posted @ 2015-07-12 21:35  gqtc  阅读(86)  评论(0编辑  收藏  举报