[LeetCode] Wildcard Matching, Solution

本文详细阐述了如何实现一种通配符模式匹配算法,该算法支持 '?' 和 '*'。其中,'?' 匹配任意单个字符,而 '*' 匹配任意序列(包括空序列)。算法通过迭代地比较输入字符串和模式字符串,以确定它们是否完全匹配。通过实例展示了算法的应用,并提供了关键代码片段。

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

» Solve this problem

[解题思路]
主要是*的匹配问题。p每遇到一个*,就保留住当前*的坐标和s的坐标,然后s从前往后扫描,如果不成功,则s++,重新扫描。

[Code]

1:    bool isMatch(const char *s, const char *p) {  
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: bool star = false;
5: const char *str, *ptr;
6: for(str = s, ptr =p; *str!=''; str++, ptr++)
7: {
8: switch(*ptr)
9: {
10: case '?':
11: break;
12: case '*':
13: star =true;
14: s=str, p =ptr;
15: while(*p=='*')
16: p++;
17: if(*p == '') // 如果'*'之后,pat是空的,直接返回true
18: return true;
19: str = s-1;
20: ptr = p-1;
21: break;
22: default:
23: {
24: if(*str != *ptr)
25: {
26: // 如果前面没有'*',则匹配不成功
27: if(!star)
28: return false;
29: s++;
30: str = s-1;
31: ptr = p-1;
32: }
33: }
34: }
35: }
36: while(*ptr== '*')
37: ptr++;
38: return (*ptr == '');
39: }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值