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

思路:正则表达式匹配分两种情况来处理:
(1)该表达式位后面紧跟的不是'*',那么只需要比较该位表达式与所遍历到字串位是否相等即可('.'匹配所有字串位)。
(2)该表达式位后面紧跟的是'*',那么这就需要进行讨论,因为不知道这个表达式位究竟包含了字串中的多少位,那么就要讨论该表达式位包含了字串中符合条件的的0位,1位,2 位...各种情况,只要其中一种情况成功匹配,那么就代表字串与正则表达式匹配成功。

public class Regular_Expression_Matching {
	public static boolean solve(char[] s,char[] p,int sIndex,int pIndex)
	{
		//s和p全部匹配则匹配成功
		if(pIndex==p.length)
			return sIndex==s.length;
		
		if(pIndex==p.length-1||p[pIndex+1]!='*')
		{
			if(sIndex<s.length&&(s[sIndex]==p[pIndex]||p[pIndex]=='.'))
				return solve(s,p,sIndex+1,pIndex+1);
			else
				return false;				
		}
		else
		{
			while(sIndex<s.length&&(s[sIndex]==p[pIndex]||p[pIndex]=='.'))
			{
				if(solve(s,p,sIndex,pIndex+2))
					return true;
				else
					sIndex++;
			}
		}
		//假如某位表达式后面既是'*',但是该位又与所遍历到的字串位不匹配,那么就要跳过这个表达式(包括其后面的'*')。
		return solve(s,p,sIndex,pIndex+2);
	}
	public static boolean isMatch(String s,String p) 
	{
		return solve(s.toCharArray(),p.toCharArray(),0,0);        
    }
	
	public static void main(String[] args) {
		String s = "aab";
		String p = ".*cd";
		System.out.println(isMatch(s,p));
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值