10. Regular Expression Matching 正则表达式匹配

题目链接
tag:

  • Hard;
  • DP;

question:
  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 = "cab"
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 = "misisp*."
Output: false

思路:
  DP来解,定义一个二维的DP数组,其中dp[i][j]表示s[0,i)和p[0,j)是否match,然后有下面三种情况:

  • P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
  • P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;
  • P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.

C++ 解法:

class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.size(), n = p.size();
        vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
        dp[0][0] = true;
        for (int i = 0; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (j > 1 && p[j - 1] == '*') {
                    dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
                } else {
                    dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
                }
            }
        }
        return dp[m][n];
    }
};

Python 解法:

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        dp = []
        defaultRow = [False] + [False for _ in p]
        dp.append(list(defaultRow))
        dp[0][0] = True
        for x in range(len(p)):
            if p[x] == '*':
                dp[0][x+1] = dp[0][x-1]

        for i in range(len(s)):
            dp.append(list(defaultRow))
            for j in range(len(p)):
                if p[j] != '*':
                    if (s[i] == p[j] or p[j] == '.') and dp[i][j]:
                        dp[i+1][j+1] = True
                elif p[j] == '.':
                    if dp[i][j]:
                        dp[i+1][j+1] = True
                else: # *
                    #匹配0次
                    if dp[i+1][j-1]:
                        dp[i+1][j+1] = True
                    #匹配1次
                    if dp[i+1][j]:
                        dp[i+1][j+1] = True
                    #匹配多次
                    if (s[i] == p[j-1] or p[j-1] == '.') and dp[i][j+1]:
                        dp[i+1][j+1] = True
        return dp[-1][-1]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,172评论 0赞 10
  • 十年之后我会是怎样呢?不怕死不迷信的你可能会想自己能不能活到十年之后。 先讲一个我听来的关于一个叫瓶儿的女孩的故...
    怎么都被用了呢阅读 385评论 0赞 0
  • 起风了 迷茫、徘徊、彷徨,太多的悲伤承载的记忆,都在这一刻结束了 睡吧!睡吧!这场梦已经结束,下一场繁华的梦等待你...
    魏幺九阅读 262评论 0赞 1
  • 我从小就像成为一个很酷的人,一个与众不同的人。 现在是凌晨五点半,据我和小郭同学待在网吧已经过去六个小时了。 我为...
    江猫渔火阅读 291评论 0赞 1
  • (摘自度娘) 这里的人的概念应该是指文化中通俗所说的人,即历史记载上的人,而非基于生物学等探讨的人。 由人化文,强...
    积步斋主人阅读 3,355评论 0赞 3

友情链接更多精彩内容