Leecode #10 Regular Expression Matching

一、 问题描述
Leecode第十题,题目为:

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

问题理解为

给定字符串s和模式p,用’.’ 和 ''实现他们之间的正则表达匹配。
‘.’ 匹配任何字母
'
'匹配前一个或者更多个元素的0
匹配应该覆盖整个输入字符串(而不是部分)
注意:
1、s可以是空的,并且只包含小写字母a-z;
2、p可以是空的,只包含小写字母a-z或.或*。

例 1:
输入
s = “aa”
p = “a”
输出: false
注: “a” 不匹配整个字符串 “aa”.

例 2:
输入:
s = “aa”
p = “a*”
输出: true
注: '*'表示前置元素重复零或多次, ‘a’. 因此,通过重复“a”一次,它就变成了 “aa”.

例 3:
输入:
s = “ab”
p = “."
输出: true
注: ".
” 表示“任何字符(.)的零或多个(*)”。

例 4:
输入:
s = “aab”
p = “cab”
输出: true
注: c 可以重复0次, a 可以重复1次. 因此它匹配"aab".

例 5:
输入:
s = “mississippi”
p = “misisp*.”
输出: false

二、解题思路

逐个字符匹配

三、实现代码

class Solution {
public:
    bool isMatch(string s, string p) {
        int x = s.length(), y = p.length(); 
        vector<vector<bool> > dp(x + 1, vector<bool> (y + 1, false));
        dp[0][0] = true;
        for (int i = 0; i <= x; i++)
            for (int j = 1; j <= y; j++)
                if (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[x][y];
    }
};
``

猜你喜欢

转载自blog.csdn.net/serena_t/article/details/90168956