zoukankan      html  css  js  c++  java
  • 66. Regular Expression Matching

    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
    
    思路: 这题 ugly 之处,在于 '*' 给的很不明朗, 其实'c*', 表示 '*' 可以代表 'ccc...cc'。
    对 '*' 的理解,若出现 p中出现 '*', 则要比较用 s 和 p 中 '*' 之前的那个元素比较,从左往右找出 s 中第一个与 p 之前的元素不同的元素。
    (若全相同,例如, 之前那个元素为 '.', 则 '.*' (表示'.......^....')可以匹配任何 s 串)。
    //垃圾题!rubbish question!
    class Solution {
    public:
        bool isMatch(const char *s, const char *p) {   
            if (s == NULL || p == NULL) return false;
            if (*p == '') return *s == '';
            // ".*" matches "", so we can't check (*s == '') here.
            if (*(p + 1) == '*'){
            // Here *p != '', so this condition equals with
            // (*s != '' && (*p == '.' || *s == *p)).
                while ((*s != '' && *p == '.') || *s == *p){
                    if (isMatch(s, p + 2)) return true;
                    ++s;
                }
                return isMatch(s, p + 2);
            }
            else if ((*s != '' && *p == '.') || *s == *p){
                return isMatch(s + 1, p + 1);
            }
        return false;
        }
    };
    











  • 相关阅读:
    axios express设置跨域允许传递cookie
    yarn常用命令指北
    Web代理工具NProxy
    DevOps的了解
    css图片hover放大
    autoprefixer
    谈谈浏览器http缓存
    欢迎使用 MWeb
    优化关键渲染路径CRP
    chrome 61 更新
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3961261.html
Copyright © 2011-2022 走看看