zoukankan      html  css  js  c++  java
  • 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 public class RegularExpressionMatching {
     2 
     3     public static void main(String[] args) {
     4         // TODO Auto-generated method stub
     5         System.out.println(isMatch("aa","a*"));
     6     }
     7     public static boolean isMatch(String s, String p) {
     8         if (p.length() == 0)
     9             return s.length() == 0;
    10 
    11         // length == 1 is the case that is easy to forget.
    12         // as p is subtracted 2 each time, so if original
    13         // p is odd, then finally it will face the length 1
    14         if (p.length() == 1)
    15             return (s.length() == 1) && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.');
    16 
    17         // next char is not '*': must match current character
    18         if (p.charAt(1) != '*') {
    19             if (s.length() == 0)
    20                 return false;
    21             else
    22                 return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && isMatch(s.substring(1), p.substring(1));
    23         } else {
    24             // next char is *
    25             while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) {
    26                 if (isMatch(s, p.substring(2)))
    27                     return true;
    28                 s = s.substring(1);
    29             }
    30             return isMatch(s, p.substring(2));
    31         }
    32     }
    33 
    34 }
  • 相关阅读:
    Tomcat基于MSM+Memcached实现Session共享
    Zabbix简介及安装
    redis简介
    Ansible详解(二)
    Ansible详解(一)
    WAMP3.1.10/Apache 设置站点根目录
    最长回文子串--轻松理解Manacher算法
    一篇文章彻底了解Java垃圾收集(GC)机制
    java内存模型详解
    Java中23种设计模式--超快速入门及举例代码
  • 原文地址:https://www.cnblogs.com/ncznx/p/9180591.html
Copyright © 2011-2022 走看看