Leetcode_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

解析:用动态规划可以解决正则匹配字符串

首先我们定义dp[i+1][j+1]表示字符串s[0…i]和p[0…j]是否匹配
那么我们首先进行初始化
dp[0][0] = 1 因为空串肯定能和空串进行匹配
i:0->n dp[i+1][0]p为空串肯定不能和s进行匹配
j:0->m dp[0][j+1] 是根据dp[0][j-1]&&p[j]==’*’

然后就是动态规划的过程了,
如果p[j]不等于* 那么dp[i+1][j+1] = dp[i][j] && s[i]==p[j]
如果p[j]等于‘’ 那么分三种情况 如果匹配0次,那么dp[i+1][j+1] = dp[i+1][j-1]
如果*匹配1次,那么dp[i+1][j+1] = dp[i+1][j]
如果*匹配2次及以上,那么dp[i+1][j+1] = dp[i][j+1]&&s[i]==p[j-1],这里可能比较难理解,比如s=aaab p=a*b
那么当i=2 j=1的时候 那么就是匹配aaa 和a* 是否匹配,在这里匹配了2个a,所以在这里的意思就是dp[3][2] = dp[2][2] &&s[2]==p[1] 意思就是判断aa和a是否匹配,如果匹配,那么只要s[i]和 * 之前的字符相同,相当于*多扩展了一个p[j]。

代码:

#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#include<stack>
using namespace std;


bool isMatch(string s, string p)
{
    int dp[s.length()][p.length()];
    int l1 = s.length();
    int l2 = p.length();
    memset(dp,0, sizeof(dp));
    dp[0][0] = 1;
    for(int i=0;i<l1;i++) dp[i+1][0] = 0;
    for(int j=0;j<l2;j++) dp[0][j+1] = j>0&&dp[0][j-1]&&p[j]=='*';
    for(int i=0;i<l1;i++)
        for(int j=0;j<l2;j++)
        {
            if(p[j]!='*') dp[i+1][j+1] = dp[i][j]&&(s[i]==p[j]||p[j]=='.');
            else
                dp[i+1][j+1] = j>0&&dp[i+1][j-1] || dp[i+1][j] || j>0&&dp[i][j+1]&&(p[j-1]=='.'||p[j-1]==s[i]);
        }
    return dp[l1][l2];
}


int main(int argc ,char* argv[])
{
    string s,p;
    while(cin>>s>>p)   cout<< isMatch(s,p)<<endl;
    return 0;
}

//aaab a*b

猜你喜欢

转载自blog.csdn.net/u014303647/article/details/80378911