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 == '?'
}
相关推荐
玖剹42 分钟前
二叉树递归题目(一)
c语言·c++·算法·leetcode
沧澜sincerely1 小时前
BFS & 图论【各种题型+对应LeetCode习题练习】
leetcode·图论·广度优先
不穿格子的程序员1 小时前
从零开始写算法——二分-寻找旋转排序数组中的最小值
数据结构·算法·leetcode·二分查找
小白程序员成长日记1 小时前
2025.11.13 力扣每日一题
算法·leetcode·职场和发展
HotCoffee-GPS4 小时前
Golang学习笔记:定时crontab
golang
_fairyland5 小时前
数据结构 力扣 练习
数据结构·考研·算法·leetcode
橘颂TA5 小时前
【剑斩OFFER】算法的暴力美学——山脉数组的蜂顶索引
算法·leetcode·职场和发展·c/c++
博语小屋6 小时前
力扣11.盛水最多的容器(medium)
算法·leetcode·职场和发展
Swift社区6 小时前
LeetCode 423 - 从英文中重建数字
算法·leetcode·职场和发展
bbq粉刷匠8 小时前
力扣--两数之和(Java)
java·leetcode