LeetCode44. 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

贪心+回溯

空间复杂度O(1)
时间复杂度约为O(n), 最坏情况O(n*n)

pos1记录扫描到的字符串s的位置,
pos2记录扫描到的字符串p的位置,
match_pos记录*匹配到的位置,
star记录*的下标,

当pos1还没有到达字符串尾,

  1. 如果pos2表示?或者pos2对应的字符等于pos1对应的字符,则表示该字符匹配,pos1,pos2都向后一步.
  2. 否则,如果pos2表示*, match_pos=pos1,star=pos2,pos2向后一步。此时*如果要匹配,首先要匹配pos1位置的字符。
  3. 否则,如果之前遇到过*,那么就利用该* 匹配一个字符,即match_pos加1. 同时更新此时的pos1,pos2。pos1=match_pos, pos2等于*的下一个字符的位置。
    bool isMatch(string s, string p) {
        int pos1 = 0, pos2 = 0;
        int match_pos = 0;
        int star = -1;

        while(pos1 < s.size()){
            if(pos2 < p.size() && p[pos2] == '?' || p[pos2] == s[pos1]){
                pos1++;
                pos2++;
            }
            else if(pos2 < p.size() && p[pos2] == '*'){
                star = pos2;
                match_pos = pos1;
                pos2++;
            }
            else if(star != -1){
                match_pos++;
                pos1 = match_pos;
                pos2 = star + 1;
            }
            else return false;
        }

        for(int i = pos2; i < p.size(); ++i)
            if(p[i] != '*') return false;

        return true;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值