zoukankan      html  css  js  c++  java
  • leetcode: Regular Expression Matching

    http://oj.leetcode.com/problems/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
     

    思路

    关键在于'*'的处理。对于类似于"a*"的情况,我们可以匹配0个'a',也可以匹配尽可能多的'a'。

     1 class Solution {
     2 public:
     3     bool isMatch(const char *s, const char *p) {
     4         if ('' == *p) { 
     5             return '' == *s;
     6         }
     7         
     8         if ('*' == *(p + 1)) {
     9             while ((*s != '') && ((*s == *p) || ('.' == *p))) {
    10                 if (isMatch(s, p + 2)) {
    11                     return true;
    12                 }
    13                 
    14                 ++s;
    15             }
    16             
    17             return isMatch(s, p + 2);
    18         }
    19         else {
    20             if ((*s != '') && ((*s == *p) || ('.' == *p))) {
    21                 return isMatch(s + 1, p + 1);
    22             }
    23             
    24             return false;
    25         }
    26     }
    27 };
  • 相关阅读:
    Spring Boot入门
    Spring MVC文件上传和下载
    Spring MVC异常处理
    SpringMVC
    linux(2)
    linux(1)
    白盒测试
    LoadRunner(8)
    LoadRunner(7)
    LoadRunner(6)
  • 原文地址:https://www.cnblogs.com/panda_lin/p/regular_expression_matching.html
Copyright © 2011-2022 走看看