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
  • 相关阅读:
    C# 微信 生活助手 空气质量 天气预报等 效果展示 数据抓取 (二)
    2014年个人总结
    是去是留?这是个问题
    电信限制ip的解决方案
    机械学习
    mac-mysql
    如何使用代码生成工具
    如何使用自定义表单和自定义流程
    test
    编程小问题001
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10544307.html
Copyright © 2011-2022 走看看