• 10. Regular Expression Matching


        /*
         * 10. Regular Expression Matching 
         * 11.29 by Mingyang
    *有一个case:isMatch("ab",".*"') return true这里*math的是.,所以有两个点,*也可以match无穷个. * For example, ab*c matches "ac", "abc", "abbbc", etc. * 一种基本的recurisive题目,matching类的题目一定要有recursive的思想,首先我们按照p的长度分类, * p的长度为0或者1都是基本case,那么当p的长度大于1的时候,如果p的第二个不为*,那么久没有保障, * 所以就必须第一个相等,或者p的为.,并且保证后面的也相等。 * 如果p的第二个为*,那么只要第一个相等,那么就验证s与p的第三位是否match,不行s就一步一步的退, * 如果连第一个都不相等,直接比较s与p的第三位是否相等。
    */ public static boolean isMatch(String s, String p) { if (p.length() == 0) return s.length() == 0; // length == 1 is the case that is easy to forget. // as p is subtracted 2 each time, so if original // p is odd, then finally it will face the length 1 if (p.length() == 1) return (s.length() == 1) && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); // next char is not '*': must match current character,还得埋头做人 if (p.charAt(1) != '*') { if (s.length() == 0) return false; else return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && isMatch(s.substring(1), p.substring(1)); }else{ // next char is *,那就无法无天了 while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { if (isMatch(s, p.substring(2)))
    //别忘了s往后走的时候验证一下,注意这个时候p并没有变! return true; s = s.substring(1); } return isMatch(s, p.substring(2)); } }
  • 相关阅读:
    java URL、HTTP与HTML+CSS
    JDK的图文安装教程
    Java之Tomcat、Dynamic web project与Servlet
    Java基础ArrayList、Servlet与Filter
    JavaMath方法、服务器与Tomcat安装与配置步骤
    关于navicat 系列软件一点击菜单栏就闪退
    Java基础之MySQL数据库与JDBC
    Java中的常用方法
    Java基础之Calendar类、JNDI之XML
    JAVAWEB基础模块开发顺序与数据访问对象实现类步骤
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5394217.html
Copyright © 2020-2023  润新知