Regular Expression Matching,regex,正則表達式匹配,利用動態規劃

問題描述:Implement regular expression matching with support for '.' and '*'.java

'.' 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

算法分析:.*能夠匹配任意字符串,例如ab匹配.*,不是說讓.匹配完a而後再去匹配*,而是*匹配的是.,也就是說(.*)==(..........),因此.*匹配全部字符串。算法

利用動態規劃,對於匹配字符串p,討論三種狀況,p長度爲0,p長度爲1,p的長度大於1(p的第二字符串爲*,p的第二個字符串不爲*)express

 

//動態規劃
public class Regex2 {
	public boolean isMatch(String s, String p) {
		// p長度爲0,邊界條件。
		if (p.length() == 0) {
			return s.length() == 0;
		}
	 
		// p長度爲1,邊界條件。
		if (p.length() == 1) {
	 
			// s長度爲0
			if (s.length() < 1) {
				return false;
			}
	        //首元素匹配有兩種狀況
			// 若是p爲.則s第一個元素和p必定匹配,若是p的第一個元素和s的第一元素相同,也必定匹配。
			else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) {
				return false;
			}
	 
			// 不然除了第一個匹配的元素外,比較其餘的元素,動態規劃的思想。
			else {
				return isMatch(s.substring(1), p.substring(1));
			}
		}
	 
		// p的第二個元素不是*,*表明0個或多個前面的元素
		if (p.charAt(1) != '*')
		{
			if (s.length() < 1) 
			{
				return false;
			}
			else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.'))
			{
				return false; 
			} 
			else 
			{
				return isMatch(s.substring(1), p.substring(1));
			}
		}
	 
		else  //p的第二個元素是*
		{
			//*表明0個前面的元素
			if (isMatch(s, p.substring(2))) 
			{
				return true;
			}
	 
			//*表明一個或多個前面的元素
			//遍歷s,若是s的i元素等於p的第一個元素,或者p的第一個元素爲.,匹配s的i+1和p的第三個元素後的字符串
			for(int i = 0; 
					i<s.length() && (s.charAt(i) == p.charAt(0) || (p.charAt(0) == '.'));
					i ++ )
			{
				if(isMatch(s.substring(i + 1), p.substring(2)))
				{
					return true;
				}
			}
			return false;
		}
	}
	public static void main(String[] args)
	{
		Regex2 reg2 = new Regex2();
		System.out.println(reg2.isMatch("aaba", ".*"));
	}
}
相關文章
相關標籤/搜索