Regular Expression Matching,regex,正则表达式匹配,利用动态规划

问题描述: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

算法分析:.*可以匹配任意字符串,例如ab匹配.*,不是说让.匹配完a然后再去匹配*,而是*匹配的是.,也就是说(.*)==(..........),所以.*匹配所有字符串。

利用动态规划,对于匹配字符串p,讨论三种情况,p长度为0,p长度为1,p的长度大于1(p的第二字符串为*,p的第二个字符串不为*)

//动态规划
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", ".*"));
	}
}
原文地址:https://www.cnblogs.com/masterlibin/p/5524623.html