• Regular Expression Matching


    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). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true


    class Solution {
    public:
        bool isMatch(const char *s, const char *p) 
        {
            int lens=strlen(s);
            int lenp=strlen(p);
            bool* check=new bool[lens+1];
            check[0]=true;
            for(int j=1;j<=lens;j++)
                check[j]=false;

            for(int i=0;i<lenp;i++)
            {
                if(p[i]!='*' && p[i+1]!='*' && p[i]!='.')
                {
                    for(int j=lens;j>=0;j--)
                        check[j]=check[j-1] && (p[i]==s[j-1]);                
                }
                if(p[i]=='.' && p[i+1]!='*')
                {
                    for(int j=lens;j>=0;j--)
                        check[j]=check[j-1];                
                }
                if(p[i+1]=='*')
                {
                    char c=p[i];                
                    if(c=='*')
                        for(int j=1;j<=lens;j++)
                            check[j]=true;
                    else if(c=='.')
                    {
                        //find the first match
                        int j=0;
                        while(check[j]==false && j<=lens) j++;
                        //then all the next match 
                        if(j<=lens)
                            for(;j<=lens;j++)
                                check[j]=true;
                    }
                    else    for(int j=1;j<=lens;j++)
                            if(check[j-1] && c==s[j-1])
                                check[j]=true;
                    i++;
                }    
                check[0]=check[0] && (p[i]=='*');
            }
            return check[lens];
        }
    };
  • 相关阅读:
    GetBuffer与ReleaseBuffer的用法,CString剖析
    Mysql 关闭自动提交
    Mysql 创建用户和数据库
    老爸陪我去面试——北漂18年(3)
    Java中的“&”和“&&”的区别
    Java常量定义
    利用Java API生成50到100之间的随机数
    Java考查“==”和equals
    列出JDK中常用的Java包
    cognos 配置
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759224.html
Copyright © 2020-2023  润新知