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 == '?'
}
相关推荐
Remember_99310 分钟前
【LeetCode精选算法】位运算专题一
java·开发语言·数据结构·leetcode·哈希算法
YuTaoShao18 分钟前
【LeetCode 每日一题】3507. 移除最小数对使数组有序 I
算法·leetcode·职场和发展
无心水1 小时前
4、Go语言程序实体详解:变量声明与常量应用【初学者指南】
java·服务器·开发语言·人工智能·python·golang·go
爱编码的傅同学1 小时前
【今日算法】LeetCode 11.盛水最多的容器 15.三数之和 283.移动0
数据结构·算法·leetcode
漫漫求1 小时前
1、IM:基础连接
开发语言·后端·golang
alphaTao1 小时前
LeetCode 每日一题 2026/1/19-2026/1/25
算法·leetcode
Swift社区1 小时前
LeetCode 382 链表随机节点
算法·leetcode·链表
老鼠只爱大米2 小时前
LeetCode经典算法面试题 #19:删除链表的倒数第N个结点(双指针、栈辅助法等多种实现方案详细解析)
算法·leetcode·链表·双指针·删除链表节点·一趟扫描
漫随流水2 小时前
leetcode回溯算法(131.分割回文串)
数据结构·算法·leetcode·回溯算法
王老师青少年编程2 小时前
2023年12月GESP真题及题解(C++七级): 商品交易
c++·题解·真题·gesp·csp·七级·商品交易