LeetCode 44. Wildcard Matching

本文深入探讨了通配符模式匹配算法,重点讲解了如何使用递归回溯和迭代方法实现模式匹配,特别是对‘*’和‘?’字符的支持。通过多个实例详细解释了算法的工作原理,并提供了一种高效的迭代解决方案。

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

44. Wildcard Matching

Given an input string (s) and a pattern §, 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.
    Example 1:

Input:

s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

Approach

题目大意: 字符串模式匹配,‘*’可以匹配任意长度的序列,包括长度为零,‘?’匹配任意一个单词
解题思路:有两种解题,一种是用递归回溯求解,需要适当剪枝。第二种是用迭代求解,有点类似AC自动机,保存上一次的状态。贴出的代码就是第二种思路,我们通过保存 p[j]==*此时的j的索引,然后继续判断下去,如果匹配不成功,恢复到上一次,将s的i的索引尝试加一个递增的数。

Code

class Solution {
public:
    bool isMatch(string s, string p) {
        int n = s.size(), m = p.size();
        if (n == 0 && m == 0)return true;
        int i = 0, j = 0, star = 0, txt = -1;
        while (i < n) {
            if (j < m && (p[j] == '?' || s[i] == p[j])) {
                j++, i++;
            } else if (j < m && p[j] == '*') {
                txt = j++;
                star = i;
            } else if (txt >= 0) {
                j = txt + 1;
                i = ++star;
            } else {
                return false;
            }
        }
        while (j < m && p[j] == '*')j++;
        return j == m;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值