(☆☆☆)52、正则表达式匹配

题目描述

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

leetcode对应题目:10. 正则表达式匹配                         题目解答

总结:题目的意思是完全匹配所有字符,而不是匹配子串,要分清和KMP的区别。所有在判断的时候一旦发现前面的匹配了,字符串str和pattern都可以向后移动了,而不用向前寻找,再重新匹配。题目中有两个字符'.'和'*'是特殊的,

class Solution {
public:
    bool isMatch(string s, string p) {
      if(p.empty())   return s.empty();
      bool firstmatch = !s.empty() && (s[0] == p[0] || p[0] == '.');
      if(p.size() >= 2 && p[1] == '*'){
        return isMatch(s,p.substr(2))  || (firstmatch && isMatch(s.substr(1),p));
      }  
      else{
        return firstmatch && isMatch(s.substr(1),p.substr(1));
      }
    }
};

char*避免string的多次拷贝:

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(*pattern == '\0')    return *str == '\0';
        bool first_match = (*str != '\0') && (*str == *pattern || *pattern == '.');
        if(*(pattern+1) == '*'){
            return match(str,pattern+2) || (first_match && match(str+1,pattern));
        }
        else{
            return first_match && match(str+1,pattern+1);
        }
    }
};

dp的解法:(转https://leetcode.com/problems/regular-expression-matching/discuss/5684/c-on-space-dp)

We define dp[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. The state equations will be:

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

i think this sentence:"P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise"should change to the "P[i][j] will be true if the s[0...i-1]==p[0....j-1]"

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(!pattern)    return str;
        int m = strlen(str),n = strlen(pattern);
        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(pattern[j-1] != '*')
                    dp[i][j] = i && dp[i-1][j-1] && (str[i-1] == pattern[j-1]|| pattern[j-1]=='.');
                else{
                    dp[i][j] = dp[i][j-2]||(i && dp[i-1][j] &&
                                 (str[i-1] == pattern[j-2]||pattern[j-2]=='.'));
                }
            } 
        }
        return dp[m][n];
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值