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());
    }
};
相关推荐
文丑颜不良啊9 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw9 小时前
C++ union 的一种妙用法
开发语言·c++
文丑颜不良啊10 小时前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu10 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步11 小时前
string的实现(1)
c++·笔记·visual studio
敲上瘾14 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯15 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251116 小时前
[C++] C++11
开发语言·c++·笔记
玄昌盛不会编程17 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊17 小时前
LeetCode3061~3080题目解析
java·leetcode