• 正则匹配-题型总结


    题目描述

    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 Solution {
     2     //考虑正则表达式
     3     public boolean isMatch(String s, String p) {
     4         if(s==null||p==null)
     5             return false;
     6         int m=s.length(),n=p.length();
     7         boolean[][]res=new boolean[m+1][n+1];
     8         res[0][0]=true;
     9         //串a,b均为
    10         for(int i=0;i<n;i++){
    11             //这是在处理a串未开始匹配时,b串出现类似于 a*a*a*a*的情况
    12             if(p.charAt(i)=='*'&&res[0][i-1])
    13                 res[0][i+1]=true;
    14         }
    15         //res[i+1][j+1]表示的是串a的前0-i个字符串与串b的前0-j个字符串是否匹配,当i,j分别走到a,b串的长度时表示匹配完成
    //注意这里p.charAt(i)里的i表示的是该串当前的字符位置,而res[i][j]里的i,j表示的是串长,如res[0][2]表示前0个a串与b串的前两个字符是否匹配
    16 for(int i=0;i<m;i++){ 17 for(int j=0;j<n;j++){ 18 if(p.charAt(j)=='.') 19 res[i+1][j+1]=res[i][j]; 20 //当b串出现'.'时,代表B串的当前位置必定能匹配a串的当前位置,所以只要前面的a,b串位置都匹配,则一直到当前位置都能匹配 21 if(p.charAt(j)==s.charAt(i)) 22 res[i+1][j+1]=res[i][j]; 23 //同理,当B串的当前位置能匹配a串的当前位置,所以只要前面的a,b串位置都匹配,则一直到当前位置都能匹配 24 if(p.charAt(j)=='*'){ 25 //当b串出现'*'时,此时要分情况讨论 26 /*如果b串的前一个位置字符,与a串当前字符不同同时b串的前一个位置不为'.',则此时不能让'*'前面的字符继续重复 27 那么此时只能让b串中'*'发挥让前一个字符重复0次的作用,让B串中的'*'与它前一个字符一起消失,那么此时a,b串当前位置能否匹配成功相当于a串不变, 28 b串向前走了两个位置的时刻是否能匹配成功 29 */ 30 if(s.charAt(i)!=p.charAt(j-1)&&p.charAt(j-1)!='.') 31 res[i+1][j+1]=res[i+1][j-1]; 32 else{ 33 //当b串出现'*'时,如果b串的前一个位置字符与(包括b为'.'的情况)a串当前位置字符相同 34 /*那么此时可以有多种做法 35 首先,我可以任性一点,让'*'和它前一个字符都消失,则当前是否能匹配成功,相当于b串少了2个字符进行匹配,即res[i+1][j+1]=res[i+1][j-1] 36 或者,让'*'发挥让前一个字符重复1次的作用,相当于'*'自己消失,此时相当于b串删了1个字符进行匹配,即 res[i+1][j+1]=res[i+1][j] 37 或者,让'*'发挥让前一个字符重复多次的作用,相当于从'*'位开始,又出现了多次'*'前面的字符 38 */ 39 res[i+1][j+1]=res[i+1][j-1]||res[i+1][j]||res[i][j+1]; 40 } 41 42 43 } 44 } 45 } 46 47 return res[m][n]; 48 } 49 }

    先记录下,有空细细研究

  • 相关阅读:
    系统设计实现
    反编译
    android layout analyze
    2016.7.20-notes
    如何认识刘昊然?
    leetcode-中等-队列-二叉树的层次遍历
    leetcode-简单-栈-逆波兰表达式
    leetcode-简单-栈-有效的括号
    队列-链式队列
    队列-循环队列-顺序存储
  • 原文地址:https://www.cnblogs.com/pathjh/p/9043943.html
Copyright © 2020-2023  润新知