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

思路:我们维护两个指针inds和indp,分别代表s和p字符串中当前要比较的位置。

如果s[inds] 等于 p[indp],或者p[indp]为'?',则匹配成功,inds和indp分别加一,进行下一次匹配。

如果p[indp]为'*',则记下当前两个字符串匹配的下标,即s_star = inds,p_star = indp。

当我们遇见*号时,*号可以与0到多个字符进行匹配,因此这里我们从匹配0个开始尝试。即令indp加1,然后开始下一轮的匹配(inds未变,而indp加1了,相当于p字符串里这个*号与s中的0个字符进行了匹配)。

当我们发现上述情况均不成立,即s[inds]和p[indp]匹配失败时,看一下p_star的值是否大于-1(初始值为-1,大于-1说明前面遇见了*号),若大于-1,说明之前有*号,然后我们尝试*号再多匹配一个字符,即我们令inds=++s_star,然后indp=p_star + 1,进行下一次迭代。

若上述条件都不成立,那肯定是匹配不上了,return false。

在实现过程中,我们通过inds < s.size()这个条件来判断迭代是否要结束。而在迭代过程中,我们要时刻保证indp < p.size()。如果在迭代中出现了indp = p.size(),说明s和p是不匹配的。

在迭代结束后,我们不能马上就下定论,因为有可能p串的末尾有多个*号我们没有进行完,而*号可以匹配0个符号,所以我们要考虑到这种情况。这里我们进行一下小处理,只要indp < p.size()且p[indp]='*',就令indp加一。

最后判断indp是否到了p串的末尾就知道是否匹配了。

 class Solution {
public:
bool isMatch(string s, string p) {
int slen = s.size(), plen = p.size();
int inds = , indp = ;
int s_star = -, p_star = -;
while (inds < slen)
{
if (indp < plen && p[indp] == '*')
{
s_star = inds;
p_star = indp++;
}
else if (indp < plen && (s[inds] == p[indp] || p[indp] == '?'))
{
inds++;
indp++;
}
else if (p_star > -)
{
inds = ++s_star;
indp = p_star + ;
}
else return false;
}
while (indp < plen && p[indp] == '*')
indp++;
return indp == plen;
}

最新文章

  1. jasig CAS 实现单点登录 - java、php客户端登录实现
  2. 349. Intersection of Two Arrays
  3. KVO KVC
  4. 洛谷 P1005 矩阵取数游戏
  5. CSS3 过滤
  6. rsyslog 读取单个文件测试
  7. android使用Genymotion作为模拟器
  8. 利用WSGI来部署你的网站
  9. python流程控制:while循环
  10. phpmailer 发送邮件(一)
  11. Java设计模式(七)Decorate装饰器模式
  12. Linux shell查询ip归属地
  13. 【BZOJ 3626】 [LNOI2014]LCA【在线+主席树+树剖】
  14. Android图片加载为什么选择glide
  15. docker 错误:Error response from daemon: cannot stop container: connect: connection refused&quot;: unknown
  16. Disconf 学习系列之Disconf 与 Diamond的横向对比(图文详解)
  17. P3355 骑士共存问题
  18. 小K的农场(差分约束,spfa)
  19. C语言调用Intel处理器CPUID指令的实例
  20. android 字符串string

热门文章

  1. Linux下 导入导出数据库
  2. loj2046 「CQOI2016」路由表
  3. 【Palindrome Partitioning】cpp
  4. MCMC 浅谈
  5. [转]手写数字识别错误NameError: name &#39;mnist&#39; is not defined
  6. nodejs、yarn编译安装
  7. Unity 碰撞检测
  8. SQL2008非域环境直接使用WINDOWS登录的镜像设置
  9. 设计模式(一)单例模式:2-懒汉模式(Lazy)
  10. js处理浮点数计算误差