zoukankan      html  css  js  c++  java
  • lc面试准备:Regular Expression Matching

    1 题目

    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

    接口

    boolean isMatch(String s, String p);

    2 思路

    基本思路就是先看字符串s和p的从i和j开始的子串是否匹配,用递归的方法直到串的最后,最后回溯回来得到结果。假设现在走到s的i位置,p的j位置,情况分为下列两种: 
    (1)p[j+1]不是'*'。情况比较简单,只要判断当前s的i和p的j上的字符是否一样(如果有p在j上的字符是'.',也是相同),如果不同,返回false,否则,递归下一层i+1,j+1; 
    (2)p[j+1]是'*'。那么此时看从s[i]开始的子串,假设s[i],s[i+1],...s[i+k]都等于p[j]那么意味着这些都有可能是合适的匹配,那么递归对于剩下的(i,j+2),(i+1,j+2),...,(i+k,j+2)都要尝试(j+2是因为跳过当前和下一个'*'字符)。 

    复杂度

    Time:O(n) Space:O(n!)

    3 代码

     1     public boolean isMatch(String s, String p) {
     2 
     3         if (p.length() == 0)
     4             return s.length() == 0;
     5 
     6         // p's length 1 is special case
     7         // next char is not '*',then must match
     8         if (p.length() == 1 || p.charAt(1) != '*') {
     9             if (s.length() < 1 || (p.charAt(0) != '.' && s.charAt(0) != p.charAt(0)))
    10                 return false;
    11             return isMatch(s.substring(1), p.substring(1));
    12         } else { // next char is '*'
    13             int len = s.length();
    14             int i = -1;
    15             while (i < len
    16                     && (i < 0 || p.charAt(0) == '.' || p.charAt(0) == s.charAt(i))) {
    17                 if (isMatch(s.substring(i + 1), p.substring(2)))
    18                     return true;
    19                 i++;
    20             }
    21             return false;
    22         }
    23     }

    4 总结

    1. 正则匹配的思路:主要是对*的处理。
    2. 对于'a*' 这种,从尽量不匹配到匹配1个a、2个a、3个a,让后看后面的匹配算式P,是否可以匹配到目标子串中。只要有一次匹配成功,便是成功的。
    3. 具体实例run的过程,请参考戴牛的3.6 Regular Expression Matching

    5 扩展

    考虑引入辅助函数,不使用substring函数来减少内存使用,使用charAt().

    6 参考

  • 相关阅读:
    QR码与DM码的对比
    JBPM在Eclipse中运行时页面错误ProcessEngine cannot be resolved to a type
    C. A Mist of Florescence
    B. A Tide of Riverscape
    A. A Blend of Springtime
    A. Gennady the Dentist
    D. Lizard Era: Beginning
    E. Jzzhu and Apples
    D. Jzzhu and Cities
    C. Jzzhu and Chocolate
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4387677.html
Copyright © 2011-2022 走看看