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());
    }
};
相关推荐
李匠202417 分钟前
C++GO语言微服务之Dockerfile && docker-compose②
c++·容器
2301_803554521 小时前
c++和c的不同
java·c语言·c++
Darkwanderor1 小时前
c++STL-通用(反向)迭代器适配器
c++
Magnum Lehar1 小时前
3d游戏引擎的Utilities模块实现
c++·算法·游戏引擎
青瓦梦滋2 小时前
【语法】C++的多态
开发语言·c++
小羊在奋斗3 小时前
【LeetCode 热题 100】反转链表 / 回文链表 / 有序链表转换二叉搜索树 / LRU 缓存
算法·leetcode·链表
爱上彩虹c3 小时前
LeetCode Hot100 (1/100)
算法·leetcode·职场和发展
Darkwanderor5 小时前
一般枚举题目合集
c++·算法
源远流长jerry5 小时前
右值引用和移动语义
c++