C++ | Leetcode C++题解之第44题通配符匹配

题目:

题解:

cpp 复制代码
class Solution {
public:
    bool isMatch(string s, string p) {
        auto allStars = [](const string& str, int left, int right) {
            for (int i = left; i < right; ++i) {
                if (str[i] != '*') {
                    return false;
                }
            }
            return true;
        };
        auto charMatch = [](char u, char v) {
            return u == v || v == '?';
        };

        while (s.size() && p.size() && p.back() != '*') {
            if (charMatch(s.back(), p.back())) {
                s.pop_back();
                p.pop_back();
            }
            else {
                return false;
            }
        }
        if (p.empty()) {
            return s.empty();
        }

        int sIndex = 0, pIndex = 0;
        int sRecord = -1, pRecord = -1;
        while (sIndex < s.size() && pIndex < p.size()) {
            if (p[pIndex] == '*') {
                ++pIndex;
                sRecord = sIndex;
                pRecord = pIndex;
            }
            else if (charMatch(s[sIndex], p[pIndex])) {
                ++sIndex;
                ++pIndex;
            }
            else if (sRecord != -1 && sRecord + 1 < s.size()) {
                ++sRecord;
                sIndex = sRecord;
                pIndex = pRecord;
            }
            else {
                return false;
            }
        }
        return allStars(p, pIndex, p.size());
    }
};
相关推荐
Larry_Yanan3 分钟前
Qt+OpenCV(一)环境搭建
开发语言·c++·qt·opencv·学习
草莓熊Lotso15 分钟前
MySQL 事务管理全解:从 ACID 特性、隔离级别到 MVCC 底层原理
linux·运维·服务器·c语言·数据库·c++·mysql
穿条秋裤到处跑24 分钟前
每日一道leetcode(2026.04.07):模拟行走机器人 II
leetcode·机器人
sheeta199827 分钟前
LeetCode 每日一题笔记 日期:2026.04.07 题目:2069.模拟行走机器人二
笔记·leetcode·机器人
im_AMBER27 分钟前
Leetcode 153 课程表 | 腐烂的橘子
开发语言·算法·leetcode·深度优先·图搜索
paeamecium29 分钟前
【PAT甲级真题】- Reversing Linked List (25)
数据结构·c++·算法·pat
田梓燊31 分钟前
leetcode 73
算法·leetcode·职场和发展
TTTrees36 分钟前
C++学习笔记(38):封装、继承、多态
c++
6Hzlia43 分钟前
【Hot 100 刷题计划】 LeetCode 54. 螺旋矩阵 | C++ 模拟法题解
c++·leetcode·矩阵
float_com1 小时前
LeetCode 88. 合并两个有序数组
leetcode