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());
    }
};
相关推荐
房开民4 小时前
c++总结
java·开发语言·c++
好大哥呀4 小时前
C++ 多态
java·jvm·c++
阿豪学编程5 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳6 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
hz_zhangrl6 小时前
CCF-GESP 等级考试 2026年3月认证C++五级真题解析
c++·青少年编程·程序设计·gesp·c++五级·gesp2026年3月·gesp c++五级
Σίσυφος19006 小时前
C++ 多肽经典面试题
开发语言·c++·面试
禹中一只鱼7 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒7 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
crescent_悦7 小时前
C++:The Largest Generation
java·开发语言·c++
paeamecium8 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试