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 == '?'
}
相关推荐
wuhen_n9 分钟前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展
Jeremy爱编码2 小时前
leetcode课程表
算法·leetcode·职场和发展
努力学算法的蒟蒻2 小时前
day46(12.27)——leetcode面试经典150
算法·leetcode·面试
元亓亓亓4 小时前
LeetCode热题100--152. 乘积最大子数组--中等
算法·leetcode·职场和发展
molaifeng4 小时前
像搭积木一样理解 Golang AST
开发语言·后端·golang
梭七y5 小时前
【力扣hot100题】(103)移动零
数据结构·算法·leetcode
Jeremy爱编码6 小时前
leetcode热题腐烂的橘子
算法·leetcode·职场和发展
alphaTao6 小时前
LeetCode 每日一题 2025/12/22-2025/12/28
算法·leetcode
小白菜又菜7 小时前
Leetcode 1523. Count Odd Numbers in an Interval Range
算法·leetcode
捧 花7 小时前
前端如何调用后端接口(HTML + JS & Vue )
服务器·golang·vue·api·前后端交互