leetcode第10题——***Regular Expression Matching

该博客介绍了LeetCode的第10题,内容涉及实现支持星号(*)和问号(?)的正则表达式匹配功能。博主详细阐述了解题思路,并提供了Python和Java两种语言的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

思路

利用递归的思想,根据匹配字符串p的下一字符是不是'*'分两种情况处理:
1. p的下个字符是'*',如果p和s当前字符相同或p当前字符是'.',则一直往右移动直到p没有'.*'或'x*'这样的情况,递归判断(x是指跟s相同的字符)
2. p的下个字符不是'*',如果p和s当前字符相同或p当前字符是'.',则p和s往右移动一个字符,递归判断
注意由于Python递归效率较差,因此用Python要尽量减小算法复杂度

代码

Python
class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        sLen = len(s)
        pLen = len(p)
        if (pLen == 0):
            return sLen == 0
        if (pLen == 1):
            if (p == s) or ((p == '.') and (len(s) == 1)):
                return True
            else:
                return False
        #p的最后一个字符不是'*'也不是'.'且不出现在s里,p跟s肯定不匹配
        if (p[-1] != '*') and (p[-1] != '.') and (p[-1] not in s):
            return False
        if (p[1] != '*'):
            if (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
                return self.isMatch(s[1:],p[1:])
            return False
        else:
            while (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
                if (self.isMatch(s,p[2:])):
                    return True
                s = s[1:]
            return self.isMatch(s,p[2:])
Java
public class Solution {
    public boolean isMatch(String s, String p){
		int sLen = s.length();
		int pLen = p.length();
		if(pLen == 0) return sLen == 0;
		if(pLen == 1){
			if(p.equals(s) || p.equals(".") && s.length() == 1) return true;
			else return false;
		}
		if(p.charAt(pLen-1) != '*' && p.charAt(pLen-1) != '.' && !s.contains(p.substring(pLen-1))) return false;
		if(p.charAt(1) == '*'){
		    //p的下个字符是'*',如果p和s当前字符相同或p当前字符是'.',则一直往右移动
			while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.' )){
				if(isMatch(s,p.substring(2))) return true;
				s = s.substring(1);
			}
			return isMatch(s,p.substring(2));
		}
		else{
		    //p的下个字符不是'*',如果p和s当前字符相同或p当前字符是'.',则p和s往右移动一个字符
			if(s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
				return isMatch(s.substring(1),p.substring(1));
			}
			return false;
		}
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值