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());
    }
};
相关推荐
优雅的潮叭7 小时前
c++ 学习笔记之 shared_ptr
c++·笔记·学习
多米Domi0117 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
SunkingYang7 小时前
QT中使用Lambda表达式作为槽函数用法,以及捕获列表和参数列表用法与区别
c++·qt·用法·lambda表达式·捕获列表·槽函数·参数列表
微露清风8 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
Lips6118 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
代码村新手9 小时前
C++-类和对象(中)
java·开发语言·c++
今天_也很困10 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
Ccjf酷儿10 小时前
C++语言程序设计 (郑莉)第十章 泛型程序设计与C++标准模板库
开发语言·c++
千金裘换酒10 小时前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
alphaTao11 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode