Golang | Leetcode Golang题解之第44题通配符匹配

题目:

题解:

Go 复制代码
func isMatch(s string, p string) bool {
    for len(s) > 0 && len(p) > 0 && p[len(p)-1] != '*' {
        if charMatch(s[len(s)-1], p[len(p)-1]) {
            s = s[:len(s)-1]
            p = p[:len(p)-1]
        } else {
            return false
        }
    }
    if len(p) == 0 {
        return len(s) == 0
    }
    sIndex, pIndex := 0, 0
    sRecord, pRecord := -1, -1
    for sIndex < len(s) && pRecord < len(p) {
        if p[pIndex] == '*' {
            pIndex++
            sRecord, pRecord = sIndex, pIndex
        } else if charMatch(s[sIndex], p[pIndex]) {
            sIndex++
            pIndex++
        } else if sRecord != -1 && sRecord + 1 < len(s) {
            sRecord++
            sIndex, pIndex = sRecord, pRecord
        } else {
            return false
        }
    }
    return allStars(p, pIndex, len(p))
}

func allStars(str string, left, right int) bool {
    for i := left; i < right; i++ {
        if str[i] != '*' {
            return false
        }
    }
    return true
}

func charMatch(u, v byte) bool {
    return u == v || v == '?'
}
相关推荐
smj2302_796826529 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
姚不倒11 小时前
从零实现一个基于 Ollama + Go + MySQL 的 Text-to-SQL 智能体(M1 实战)
sql·mysql·云原生·golang
医用门11 小时前
医院用门一线品牌
leetcode
he___H13 小时前
leetcode100-普通数组
java·数据结构·算法·leetcode
菜菜的顾清寒16 小时前
力扣HOT100(30)两两交换链表中的节点
算法·leetcode·链表
csdn_aspnet18 小时前
C++ 算法 LeetCode 编号 70 - 爬楼梯
开发语言·c++·算法·leetcode
圣保罗的大教堂18 小时前
leetcode 2770. 达到末尾下标所需的最大跳跃次数 中等
leetcode
wlsh1519 小时前
Go 泛型笔记
golang
姚不倒19 小时前
从「LeetCode LRU 缓存」到「生产级 Go Web 服务」:我如何迈出工程化第一步
leetcode·缓存·云原生·golang
sheeta199819 小时前
LeetCode 每日一题笔记 日期:2026.05.25 题目:1871. 跳跃游戏 VII
笔记·leetcode·游戏