leetcode 10: Regular Expression Matching 分析及解答

来源:互联网 发布:淘宝首页轮播图多大 编辑:程序博客网 时间:2024/06/07 03:32


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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

解读:

  • ‘.'代表一个任意字符,与其附近的字符无关
  • ’*‘代表o个或者多个前面的字符,该字符影响前面字符的“存在”,例如:a*={ε,a,aa,aaa,…},即当"*"表示0个前面的字符时,该字符串为空串ε。

分析:题目要求匹配整个输入字符串,即完全匹配,分如下情况:

  1. 同时为空则true
    p为ε时,s为ε则匹配
    s为ε时,p为ε则匹配,但此时p分两种情况:
      1、p确实为ε
      2、p为”a*“类型,此时*代表前面的字符存在0次,则p在匹配意义上位ε
  2. 不同时为空就需要比较
  • p字符串中当前字符是否匹配与其下一个是否为’*‘有关,所以分两种情况
    [p+1]=='*' 则 匹配当前字符或者匹配下两个字符[p+2](即不匹配当前字符,此时*表示当前字符出现零次,即p=ε[p+2])
    [p+1]!='*' 对当前字符进行匹配

请看代码:

public class Solution {    public boolean isMatch(String s, String p) {       //1、字符同时为空的情况       //1.1先考虑p为空,此时只要看s是否为空即可。       if(p.length()==0) return s.length()==0;       //1.2 再考虑s为空的情况       else if(s.length()==0)       {       //1.2.1 p分两种情况           //if(p.length()==0)return true;//情况1 p确实为空。           if(p.length()>1&&p.charAt(1)=='*')return isMatch(s,p.substring(2));//情况二,”匹配“意义上为空           else return false;       }       //2、不同时为空则进行匹配       else        {            //2.1 如果p的下一个字符为’*‘则分两种情况           if(p.length()>1&&p.charAt(1)=='*')           {    //2.1.1 匹配下两个字符           if(isMatch(s,p.substring(2))) return true;     //2.1.2 匹配当前字符,注意:此时p字符串不步进           else if(s.charAt(0)==p.charAt(0)||p.charAt(0)=='.')return isMatch(s.substring(1),p);           else return false;           }            //2.2 匹配当前字符           else           {              if(s.charAt(0)==p.charAt(0)||p.charAt(0)=='.')return isMatch(s.substring(1),p.substring(1));              else return false;           }       }    }}







0 0
原创粉丝点击