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());
    }
};
相关推荐
jinyishu_5 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm5 小时前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
什巳6 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
hold?fish:palm8 小时前
RDB全量快照备份
c++·redis·后端
什巳8 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826528 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
盐焗鹌鹑蛋9 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
ComputerInBook11 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
AA陈超12 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
bu_shuo12 小时前
c与cpp中的argc和argv
c语言·c++·算法