10. Regular Expression Matching

本文介绍了一种实现正则表达式匹配的递归算法,该算法支持‘.’和‘*’两种特殊字符,其中‘.’可以匹配任意单个字符,而‘*’则可以匹配其前一个元素零次或多次。文章通过具体的Java代码示例详细解释了如何处理这两种特殊字符,并给出了几种典型情况下的匹配结果。

只能说这样的题太烧脑了,只好在Discussion中找答案


考虑递归的方法,分别考虑第二位上有没有 * ,如果没有,就先比较第一位,接着递归比较后面的子字符串;

如果有 * 的话,那么*可能匹配多个字符串,用while循环,匹配一个时判断两个字符串后面的子串是不是match,是就return true,否则匹配两个在看,不行再三个,知道两个字符串的子串的第一个字符不匹配。


要注意一点的是C++与Java操作子串的区别



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

package l10;

public class Solution {
	
	public boolean matchFirst(String s, String p) {
		if("".equals(s) || "".equals(p))	return "".equals(s) && "".equals(p);
		String st = s.substring(0, 1), pt = p.substring(0, 1);
		return st.equals(pt) || (".".equals(pt) && !"".equals(st));
	}
	
    public boolean isMatch(String s, String p) {
    	if("".equals(p))	return "".equals(s);
    	if(p.length() == 1)	return s.length() == 1 && matchFirst(s, p);
    	if(!"*".equals(p.substring(1, 2))) {
    		if(! matchFirst(s, p))	return false;
    		return isMatch(s.substring(1), p.substring(1));
    	} else {
    		if(isMatch(s, p.substring(2)))	return true;
    		while(matchFirst(s, p)) {
    			s = s.substring(1);
    			if(isMatch(s, p.substring(2)))	return true;
    		}
    	}
    	
        return false;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值