• Wildcard Matching


    题目:

    Implement wildcard pattern matching with support for '?' and '*'.

    '?' Matches any single character.
    '*' Matches any sequence of characters (including the empty sequence).
    
    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", "*") → true
    isMatch("aa", "a*") → true
    isMatch("ab", "?*") → true
    isMatch("aab", "c*a*b") → false

    这个题目真是晕了,之前有一题正则表达式 ,那题搞定了以为这个也简单,结果用递归的方法直接超时了。后来看到leetcode讨论区里面用动态规划去解的方法,看了一下还是有点繁琐,空间复杂度也较大。后来又找到另外的方法,这个叫uniagle的同学把‘*’作为分隔符先拆分再逐个匹配的。感觉还是有点繁琐,应该有更好的办法,于是找到了另一个实现,这个方法很喜欢,因此自己按这个方法搞一波,妥妥地过了。

     1     bool isMatch(const char *s, const char *p) {
     2         /*recusive version
     3         if(*p=='?') {
     4             if(*s=='')
     5                 return false;
     6             else
     7                 return isMatch(s+1,p+1);
     8         }
     9         if(*p=='*'&&*(p+1)=='') return true;
    10         
    11         if(*p=='*'){
    12             while(*p=='*') p++;
    13             for(int i=0;*(s+i)!='';i++){
    14                 if(isMatch(s+i,p))
    15                     return true;
    16             }
    17             return false;
    18         }
    19         if(*s==*p) return isMatch(s+1,p+1);
    20         else return false;
    21         */
    22         // loop
    23         const char *str,*ptr;
    24         bool hasStar=false;
    25         for(str=s,ptr=p;*str;str++){
    26             if(*ptr=='?'){
    27                 if(*s=='') return false;
    28                 else ptr++;
    29             }
    30             else if(*ptr=='*'){
    31                 hasStar=true;
    32                 while(*ptr=='*') ptr++;
    33                 if(*ptr=='') return true;
    34                 p=ptr;
    35                 s=str;
    36                 str--;
    37             }
    38             else if(*ptr==*str){
    39                 ptr++;
    40             }
    41             else if(!hasStar) 
    42                 return false;
    43             else{
    44                 ptr=p;
    45                 str=s;
    46                 s++;
    47             }
    48         }
    49         while(*ptr=='*') ptr++;
    50         return *ptr=='';
    51     }

    注释掉的是递归方法,非常简单的版本。完了之后又在网上逛了一下,发现有一个通配符算法总结,这个就比较全了。

  • 相关阅读:
    使用nginx部署Yii 2.0yii-advanced-app-2.0.6
    yii-basic-app-2.0.5/basic/config/web.php
    PS显示图像大小快捷键
    说说c, c++ 和 go
    十分钟搭建自己的私有NuGet服务器-BaGet(转)
    Redis面试总结&史上最全Redis面试题及答案(转)
    Kubernetes之helm部署使用(转)
    Kubernetes RBAC 详解(转)
    Kubernetes 集群安全机制详解(转)
    Repository 返回 IQueryable?还是 IEnumerable?(转)
  • 原文地址:https://www.cnblogs.com/mike442144/p/3479314.html
Copyright © 2020-2023  润新知