Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.express

 

'.' Matches any single character.spa

'*' Matches zero or more of the preceding element.prototype

 

The matching should cover the entire input string (not partial).blog

 

The function prototype should be:element

bool isMatch(const char *s, const char *p)input

 

Some examples:string

isMatch("aa","a") falseit

isMatch("aa","aa") trueio

isMatch("aaa","aa") falsefunction

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));  
	}  
} 
相關文章
相關標籤/搜索