zoukankan      html  css  js  c++  java
  • leetcode第十题--Regular Expression Matching

    Problem: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

    就是正则表达式,可以百度一下先学习什么事正则表达式。*号是表示前面一个字符出现零次或者多次。例如 zo*能和z匹配是因为此处*表示前面的字符o出现零次,所以和z匹配,同理,zo*还可以和zo或者zoo,zoooo,zooooooooo等等匹配。点‘.’是通配符,匹配任意一个单字符。那么点星‘.*’就可以匹配任意多个字符,因为*表示前面的任意多个重复。所以就是任意多个‘.’的重复,而‘.’又是任意匹配,所以就是任意组合都可以。第一个点匹配a第二个点并不是只能匹配a,还是可以匹配任意的字符。所以‘.*’确实是万能的。应该没有理解错误吧。 然后这题,考虑了很久,都没有想到好的思路,不得不用递归。

    class Solution {
    public:
    bool isMatch(const char *s, const char *p)
    {
        if(s == NULL || p == NULL)
            return false;
        if (*p == '')
            return *s == '';
    
        if (*(p + 1) == '*')
        {
            while(*s == *p || *p == '.' && *s != '')
            {
                if (isMatch(s, p + 2))
                    return true;
                s++;
            }
            return isMatch(s, p + 2);
        }
        else if (*s == *p || *p == '.'&&*s!='')
            return isMatch(s + 1, p + 1);
        return false;
    }
    };

    提交尝试好多次把 if (*p == '') return *s == ''; 忽略。因为是递归的,所以不能没有。这里的'.'不能对应‘’

    也可以参考这位同学的。

  • 相关阅读:
    Lucene.NET中Field.Index 和 Field.Store的几种属性的用法
    WP7学习笔记(三)
    sql注入
    JSP数据库开发实例
    oracle命令大全(转)
    .net个人涉及
    JavaScript的错误处理之onerror事件的使用方法
    脚本问题。调试
    做到了,你就成熟
    ea8.0
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4023437.html
Copyright © 2011-2022 走看看