zoukankan      html  css  js  c++  java
  • 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
    class Solution {
    public:
        bool isMatch(const char *s, const char *p) 
        {
            int len1=strlen(p);
            int len2=strlen(s);    
            
            //consider the last case.....
            int len=len1;
            for(int i=0;i<len1;i++)
                if(p[i]=='*') len--;
            if(len>len2) return 0;
            
            bool* match=new bool[len2+1];                            
            for(int j=1;j<=len2;j++) match[j]=false;
            match[0]=true;

            for(int i=1;i<=len1;i++)
            {
                if(p[i-1]=='*')
                {                
                    for(int j=1;j<=len2;j++)
                    {
                        if(match[j-1]) match[j]=true;
                    }
                }
                else if(p[i-1]=='?')
                    for(int j=len2;j>=1;j--)
                    {
                        if(match[j-1]) match[j]=true;
                        else match[j]=false;
                    }
                else
                    for(int j=len2;j>=1;j--)
                    {
                        if(match[j-1] && p[i-1]==s[j-1]) match[j]=true;
                        else match[j]=false;
                    }
                if(match[0] && p[i-1]=='*') match[0]=true;
                else match[0]=false;
            }
            return match[len2];
        }
    };
  • 相关阅读:
    HashMap源码分析和应用实例的介绍
    Map不同具体实现类的比较和应用场景的分析
    Set集合架构和常用实现类的源码分析以及实例应用
    深入理解JVM(7)——类加载器
    深入理解JVM(5)——HotSpot垃圾收集器详解
    PoolManager 简单使用
    HDU4786_Fibonacci Tree
    UVA11653_Buses
    UVA11625_Lines of Containers
    HDU3507_Print Article
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759360.html
Copyright © 2011-2022 走看看