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 }
  • 相关阅读:
    python爬虫---selenium库的用法
    Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
    python字符串截取、查找、分割
    jupyter notebook快捷键使用指南
    python中防止字符串转义
    Python之print()函数
    使用腾讯电脑管家清理电脑后,上不了网了
    Python正则表达式指南
    python之format函数
    python安装media报错
  • 原文地址:https://www.cnblogs.com/ncznx/p/9180591.html
Copyright © 2011-2022 走看看