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
  • 相关阅读:
    shell 中"${b2}" and "${b:2}"
    关于 libpcap的安装
    ubuntu adsl 上网
    2011.1.18 运算符优先级
    Tail Queues
    fd_set struct
    读取和修改操作array 配置文件的方法
    smarty调试方法
    一个CURL例子
    cakephp数据库事务transactions
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10544307.html
Copyright © 2011-2022 走看看