zoukankan      html  css  js  c++  java
  • 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];
        }
    };
  • 相关阅读:
    android.mk文件里的通配符
    vi常用命令
    如何用ndk-stack察看android崩溃堆栈
    初识lua
    c++标准库中几个常见的数据结构的区别和应用规则
    玩转ubuntu FAQ
    c++0x新特性实例(比较常用的)
    cocos2d-x的Android工程开启c++0x特性
    随笔 — 致2018.
    CPU或内存占用过高时,发生了什么
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759224.html
Copyright © 2011-2022 走看看