【剑指offer】【leetcode】正则表达式匹配
【剑指offer】【leetcode】正则表达式匹配
当第二个字母为*并且第一个字母匹配的时候,有三种情况

  1. abc 和 ab*c匹配:s + 1 pattern + 2
  2. abbc 和 ab*c匹配 : s + 1 pattern不变
  3. aaa 和 aa*aa匹配:s不变,pattern+2
    因此可以写成递归的形式:
    代码如下:
# -*- coding:utf-8 -*-
class Solution:
    # s, pattern都是字符串
    def matchCore(self, s, pattern, startS, startP):
        #print(startS, startP)
        if startS == len(s) and startP == len(pattern):
            return True
        if startP < len(pattern) - 1 and pattern[startP + 1] == '*':
            if (startS < len(s) and pattern[startP] == s[startS]) or (pattern[startP] == '.' and startS < len(s)):
                 # abc  和 ab*c匹配
                 # abbc 和 ab*c匹配
                 # aaa  和 aa*aa匹配
                return self.matchCore(s, pattern, startS + 1, startP + 2) or \
                    self.matchCore(s, pattern, startS + 1, startP) or \
                    self.matchCore(s, pattern, startS, startP + 2)
            else:
                return self.matchCore(s, pattern, startS, startP + 2)     #*前面的字母不一样,直接跳过*
        if startS < len(s) and startP < len(pattern):   #必须要判断是否越界
            if pattern[startP] == '.' or pattern[startP] == s[startS]:
                return self.matchCore(s, pattern, startS + 1, startP + 1)
        return False
    def match(self, s, pattern):
        # write code here
        if s == '' and pattern == '':
            return True
        return self.matchCore(s, pattern, 0, 0)
print(Solution().match('a','.'))

这个代码在牛客网上运行通过,在leetcode上面会超时,可能递归调用太深。leetcode上AC的代码:

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        # 判断匹配规则是否为空
        if p == "":
            # p为空的时候,判断s是否为空,则知道返回True 或 False
            return s == ""
        # 判断匹配规则是否只有一个
        if len(p) == 1:
            # 判断匹配字符串长度是否为1,和两者的第一个元素是否相同,或匹配规则使用.
            return len(s) == 1 and (s[0] == p[0] or p[0] == '.')
        # 匹配规则的第二个字符串不为*,当匹配字符串不为空的时候
        # 返回 两者的第一个元素是否相同,或匹配规则使用. and 递归新的字符串(去掉第一个字符的匹配字符串 和 去掉第一个字符的匹配规则)
        if p[1] != "*":
            if s == "":
                return False
            return (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:], p[1:])
        # 当匹配字符串不为空 and (两者的第一个元素是否相同 or 匹配规则使用.)
        while s and (s[0] == p[0] or p[0] == '.'):
            # 到了while循环,说明p[1]为*,所以递归调用匹配s和p[2:](*号之后的匹配规则)
            # 用于跳出函数,当s循环到和*不匹配的时候,则开始去匹配p[2:]之后的规则
            if self.isMatch(s, p[2:]):
                return True
            # 当匹配字符串和匹配规则*都能匹配的时候,去掉第一个字符成为新的匹配字符串,循环
            s = s[1:]
        # 假如第一个字符和匹配规则不匹配,则去判断之后的是否匹配
        return self.isMatch(s, p[2:])

相关文章:

  • 2021-09-21
  • 2022-02-14
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2021-10-04
  • 2022-02-23
  • 2021-12-28
猜你喜欢
  • 2021-07-19
  • 2021-08-16
  • 2021-11-25
  • 2022-03-05
  • 2022-12-23
相关资源
相似解决方案