zoukankan      html  css  js  c++  java
  • 44. 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
    

      

     代码来自:https://leetcode.com/problems/wildcard-matching/discuss/

    几种情况:

    一:遇到“*” 就记录此时s及p的位置istar及jstar,s向后移,p保持“*”。

    二:当s[i]=p[j]或者p[j] = "?"时,就同时向后移,(不在if,也不在else的if中出现,就默认自动同时向后移)

    三:遇到s[i] != p[j],而且p也不等于“?”,此时发生不匹配,那就判断p中是否有已出现过“*”,若p中出现过“*”,p回到"*"的位置jstar,s回到istar+1.

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int  slen = s.size(), plen = p.size(), i, j, iStar=-1, jStar=-1;
    
            for(i=0,j=0 ; i<slen; ++i, ++j)
            {
                if(p[j]=='*')  //meet a new '*', update traceback i/j info
                { 
                    iStar = i;
                    jStar = j;
                    --i;
                }
                else
                { 
                    if(p[j]!=s[i] && p[j]!='?')
                    {  // mismatch happens
                        if(iStar >=0)  // met a '*' before, then do traceback
                        { 
                            i = iStar++;
                            j = jStar;
                        }
                        else return false; // otherwise fail
                    }
                }
            }
            while(p[j]=='*') ++j;
            return j==plen;
        }
    };
  • 相关阅读:
    在命令提示符中使用antlr
    Migrating to Rails 2.0.2
    从AJAX IN ACTION书中学用 RSS READER
    maple download url
    搜索
    发邀请在线RoR开发与部署环境www.heroku.com
    if can't use ruby in command line
    查询表中某字段有重复记录的个数
    WPF窗体自适应分辨率
    《思考,快与慢》
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7881666.html
Copyright © 2011-2022 走看看