[String]010 Regular Expression Matching***

  • 分类:String

  • 考察知识点:String/DP/case by case

  • 最优解时间复杂度:O(n*m)

  • 最优解空间复杂度:O(n*m)

10. Regular Expression Matching

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

代码:

我的方法:

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """

        #给定数组的长度和宽度
        dp=[[False for i in range(len(p)+1)] for i in range(len(s)+1)]
        dp[0][0]=True

        #预处理*a=empty的情况
        for i in range(0,len(p)):
            if p[i]=="*":
                dp[0][i+1]=dp[0][i-1]

        #正常的情况
        for i in range(0,len(s)):
            for j in range(0,len(p)):
                #3种大情况
                if s[i]==p[j]:
                    dp[i+1][j+1]=dp[i][j]
                elif p[j]==".":
                    dp[i+1][j+1]=dp[i][j]
                elif p[j]=="*":
                    #两种小情况 等与不等
                    if s[i]!=p[j-1] and p[j-1]!=".":
                        dp[i+1][j+1]=dp[i+1][j-1]
                    else:
                        #三种情况 a=a* aa=a* empty=a*
                        dp[i+1][j+1]=dp[i+1][j] or dp[i][j+1] or dp[i+1][j-1]

        return dp[-1][-1]

讨论:

1.这道题十分的重要,是一道十分重要的DP题,会经常考到,一定要会!
2.DP的题目要多加一横行和一纵列,因为初始化dp[0][0]=true的需要
3.在Python中出现一个意外状况我使用

[[False]*len(s+1)]*len(p+1)]
dp[0][0]=True

竟然第一列全部都变成了True,这可能是因为只是list*n的时候指针复制地址不会变化
4.还有个自己编程的时候没注意的错误s[i]!=p[j-1] and p[j-1]!=".",只有这种情况下才需要回退
5.TestCase中竟然有""与".*",所以这道题目其实一开始根本就不需要考虑所谓的特殊情况,因为dp已经把所有的特殊情况囊括了

[String]010 Regular Expression Matching***_第1张图片
这道题确实需要细细琢磨!

你可能感兴趣的:([String]010 Regular Expression Matching***)