• 10. 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
     1 /**
     2  * @param {string} s
     3  * @param {string} p
     4  * @return {boolean}
     5  */
     6 var isMatch = function(s, p) {
     7     
     8     
     9     //首先最简单的是 s,p中都不出现正则元字符 这样如果s==p 就ok
    10     //问题是出现了元字符 比如+ * 这种就比较麻烦,我想到的是直接用分治
    11     //举例来说  s->"abcd"  p->"ae*bcd"  我们在比较 b和e时候,很快又发现e后面有个*,这个时候我们可以分类去比较
    12     //一种是去比较  bcd bcd   一种是去比较 bcd 和 e*bcd 
    13     
    14     //最后我们还要考虑 . 这个字符,因为他通配
    15     
    16      
    17     var slen = s.length;
    18     var plen = p.length;
    19     
    20     if(plen == 0){
    21 
    22         return  slen == 0;
    23     }
    24 
    25     if ('*' == p[1]){
    26            
    27         //一种就是直接把*当成0次,
    28         //另外一种就是直接当成一次。
    29            return (isMatch(s, p.substr(2)) || slen!== 0 && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p));
    30     }else{
    31            return  slen!== 0 && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p.substr(1));
    32     }
    33            
    34     
    35 };
  • 相关阅读:
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    预习非数值数据的编码方式
    计算机组成与系统结构作业01
    C语言||作业01
  • 原文地址:https://www.cnblogs.com/huenchao/p/7641877.html
Copyright © 2020-2023  润新知