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());
    }
};
相关推荐
阿豪只会阿巴1 天前
【多喝热水系列】从零开始的ROS2之旅——Day4
c++·笔记·python·ros2
2401_841495641 天前
【LeetCode刷题】寻找重复数
数据结构·python·算法·leetcode·链表·数组·重复数
郭涤生1 天前
fmtlib/fmt仓库熟悉
c++
Stanford_11061 天前
【2026新年启程】学习之路,探索之路,技术之路,成长之路……都与你同行!!!
前端·c++·学习·微信小程序·排序算法·微信开放平台
郝学胜-神的一滴1 天前
Linux线程属性设置分离技术详解
linux·服务器·数据结构·c++·程序人生·算法
leoufung1 天前
LeetCode 120. Triangle:从 0 分到 100 分的思考过程(含二维 DP 与空间优化)
linux·算法·leetcode
w-w0w-w1 天前
C++构造函数初始化列表全解析
c++
梵尔纳多1 天前
初识 OpenGL
c++·图形渲染
王老师青少年编程1 天前
2025年12月GESP(C++二级): 黄金格
c++·算法·gesp·csp·信奥赛·二级·黄金格
一起搞IT吧1 天前
相机Camera日志实例分析之十二:相机Camx【萌拍后置zoom拍照】单帧流程日志详解
android·c++·数码相机·智能手机