zoukankan      html  css  js  c++  java
  • 【LeetCode 10】正则表达式匹配

    题目链接

    【题解】

    看到这个[题解](https://leetcode-cn.com/problems/regular-expression-matching/solution/ji-yu-guan-fang-ti-jie-gen-xiang-xi-de-jiang-jie-b/) 写的代码。 就是加个备忘录法。优化一下暴力的做法。 匹配的时候如果遇到*号的话,就两种可能。不再考虑它前面一个字符了。 跳过这个*或者。或者继续用*前面那个字符匹配。 即dfs(i,j+2) 不和他匹配了 && (i和j能匹配且j+1是个*则继续复制一个和其匹配,dfs(i+1,j)) 当然,还得尝试一下不用*通配符了(s1[i]==s2[j])然后直接看看dfs(i+1,j+2)能不能匹配

    【代码】

    class Solution {
    public:
        map<pair<int,int>,bool> dic;
        int len1,len2;
        
        bool ok(string &s1,string &s2,int i,int j){
            if (dic.find(make_pair(i,j))!=dic.end()) return dic[make_pair(i,j)];
            //cout<<"**"<<i<<" "<<j<<endl;
            if (i==len1){
                if (j==len2){
                    return true;
                }
                //j!=len2不代表一定不能匹配。可能后面有*号
            }
            if (j==len2) return false;
            bool firstmatch = false;
            if (i<len1 && (s1[i]==s2[j] || s2[j]=='.')) firstmatch=true;
    
            //能够匹配到
                    //cout<<i<<" "<<j<<" "<<firstmatch<<endl;
            if (firstmatch && ok(s1,s2,i+1,s2[j+1]=='*'?j+2:j+1)) return true; //j+1是通配符的话,要跳过它。
            if (j+1==len2 || s2[j+1]!='*') return false;
            //j+1<len2 && s2[j+1]=='*'
    
            bool ju = ok(s1,s2,i,j+2) || (firstmatch && ok(s1,s2,i+1,j));
            dic[make_pair(i,j)] = ju;
            return ju;
        }
        
        bool isMatch(string s, string p) {
            dic.clear();
            len1 = s.size();len2 = p.size();
            return ok(s,p,0,0);
        }
    };
    
  • 相关阅读:
    Mayan游戏 (codevs 1136)题解
    虫食算 (codevs 1064)题解
    靶形数独 (codevs 1174)题解
    黑白棋游戏 (codevs 2743)题解
    神经网络 (codevs 1088) 题解
    The Rotation Game (POJ 2286) 题解
    倒水问题 (codevs 1226) 题解
    银河英雄传说 (codevs 1540) 题解
    生日蛋糕 (codevs 1710) 题解
    第一章 1.11 高阶函数
  • 原文地址:https://www.cnblogs.com/AWCXV/p/11797115.html
Copyright © 2011-2022 走看看