zoukankan      html  css  js  c++  java
  • 简单模拟正则表达式匹配字符串

    输入字符串s,p,p中可能包含字符"."和"*":使用正则表达式的规则判断s和p是否匹配

    示例:

      输入:s="abc" p =".*c"

      输出:True

    Python解决方案:

    class Solution(object):
        def isMatch(self, s, p):
            """
            :type s: str
            :type p: str
            :rtype: bool
            """
            len_p = len(p)
            len_s = len(s)
            if len_p == 0:
                return len_s == 0
            judge = len_s > 0 and p[0] in [".",s[0]]
            if len_p > 1 and p[1] == "*":
                if judge:
                    return self.isMatch(s[1:],p) or self.isMatch(s,p[2:])
                else:
                    return self.isMatch(s,p[2:])
            else:
                return judge and self.isMatch(s[1:],p[1:])

    改进方案(转自leetcode用csler):

    class Solution:
        def __init__(self):
            self.cache = {}
        def isMatch(self, s: 'str', p: 'str') -> 'bool':
            if len(p) == 0:     return len(s) == 0
            question = s + '+' + p
            if question in self.cache:
                return self.cache[question]
            firstMatch = len(s) > 0 and (p[0] == s[0] or p[0] == '.')
            if len(p) > 1 and p[1] == '*':
                if firstMatch:
                    res = self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
                else:
                    res = self.isMatch(s, p[2:])
            else:
                res = firstMatch and self.isMatch(s[1:], p[1:])
            self.cache[question] = res
            return res
  • 相关阅读:
    ajax的基础知识
    前端必备的php的基础知识点
    关于事件的简单汇总
    Django rest-framework(目录)
    Django(目录)
    前端(目录)
    数据库知识(目录)
    数据库基础
    并发编程(目录)
    网络编程
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10544307.html
Copyright © 2011-2022 走看看