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());
    }
};
相关推荐
XiYang-DING17 小时前
【LeetCode】Hash | 136.只出现一次的数字
算法·leetcode·哈希算法
tankeven17 小时前
HJ176 【模板】滑动窗口
c++·算法
OxyTheCrack17 小时前
【C++】一文详解C++智能指针自定义删除器(以Redis连接池为例)
c++·redis
whitelbwwww18 小时前
C++基础--类型、函数、作用域、指针、引用、文件
开发语言·c++
leaves falling18 小时前
C/C++ const:修饰变量和指针的区别(和引用底层关系)
c语言·开发语言·c++
tod11318 小时前
深入解析ext2文件系统架构
linux·服务器·c++·文件系统·ext
不想写代码的星星18 小时前
C++ 类型萃取:重生之我在幼儿园修炼类型学
c++
比昨天多敲两行18 小时前
C++11新特性
开发语言·c++
xiaoye-duck18 小时前
【C++:C++11】核心特性实战:详解C++11列表初始化、右值引用与移动语义
开发语言·c++·c++11
睡一觉就好了。18 小时前
二叉搜索树
c++