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());
    }
};
相关推荐
进击的圆儿5 分钟前
高并发内存池项目开发记录 - 02
开发语言·c++·实战·项目·内存池
YXXY3137 分钟前
二叉树进阶
c++
夜晚中的人海16 分钟前
【C++】使用双指针算法习题
开发语言·c++·算法
怀旧,18 分钟前
【Linux系统编程】3. Linux基本指令(下)
linux·开发语言·c++
艾莉丝努力练剑19 分钟前
【C++STL :stack && queue (三) 】优先级队列的使用以及底层实现
linux·开发语言·数据结构·c++·stl
earthzhang20214 小时前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
AA陈超6 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
纵有疾風起7 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
承渊政道9 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
孤独得猿9 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd