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());
    }
};
相关推荐
吃着火锅x唱着歌27 分钟前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
欧阳x天29 分钟前
C++入门(一)
c++
小张成长计划..36 分钟前
【C++】:priority_queue的理解,使用和模拟实现
c++
Dream it possible!1 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
Wenhao.1 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
吃着火锅x唱着歌1 小时前
LeetCode 1679.K和数对的最大数目
算法·leetcode·职场和发展
im_AMBER1 小时前
Leetcode 57
笔记·学习·算法·leetcode
im_AMBER1 小时前
Leetcode 58 | 附:滑动窗口题单
笔记·学习·算法·leetcode
sin_hielo1 小时前
leetcode 2154
算法·leetcode
云泽8081 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list