44 Wildcard Matching

本文详细阐述了如何实现支持问号和星号的通配符匹配算法,包括解决星号匹配的问题及其处理多种匹配场景的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

44 Wildcard Matching

链接:https://leetcode.com/problems/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(string s, string 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

Hide Tags Dynamic Programming Backtracking Greedy String
Hide Similar Problems (H) Regular Expression Matching

这个问题就是字符串匹配问题,常用在文件查找中。解决这个问题最关键的处里 * 的匹配问题。先来看需要处理的几种情况。

string sstring p*匹配的内容
h*?
hi*ih
abcaa*abc
abcadaa*abcad
abcadacda*a*dbca dac

可以这样解决,一旦遇到p中的 * 那么我们将p中的位置pstar记录下来,pstar表示p中 * 的位置,pstar只有在遇到下一个 * 才会进行更新。同时记录s中的位置为starmatch,starmatch表示 p 中 * 匹配s中最后一个字符的位置,starmatch经常要进行更新。需要注意的是当有pstar存在时,遇到不匹配的情况时候一定要更新starmatch。

class Solution {
public:
    bool isMatch(string s, string p) {
      int p1=0,p2=0,pstar=-1,starmatch=-1;
      while(p1<s.length())
      {
          if(s[p1]==p[p2]||p[p2]=='?')
          {
             p1++;
             p2++;
          }
          else if(p[p2]=='*')
          {
             pstar=++p2;
             starmatch=p1;
          }
          else if(pstar>-1)
          {
             p2=pstar;
             p1=++starmatch;
          }
          else
              return false;
      }
      while(p[p2]=='*')p2++;
      return p[p2]=='\0';
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值