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 == '?'
}
相关推荐
LK_0714 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi14 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊15 小时前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路18 小时前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
利威尔xu18 小时前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
Pniubi19 小时前
力扣239.滑动窗口最大值(优先队列)
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3281~3300题目解析
java·leetcode
利威尔xu2 天前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
文丑颜不良啊2 天前
LeetCode3261~3280题目解析
java·leetcode
Rain的Java大神之路2 天前
LeetCode 40 组合总和 II:面试官想听的不是回溯,而是那行去重代码
java·leetcode·面试