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 == '?'
}
相关推荐
To_OC7 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode
海石15 小时前
【JS击败90%】前缀和+定长滑动窗口
算法·leetcode
Tisfy15 小时前
LeetCode 2685.统计完全连通分量的数量:DFS求每个连通块的边点数
算法·leetcode·深度优先··题解·连通图·全连通分量
海石15 小时前
1次遍历,空间复杂度击败100%,时间复杂度击败85%
算法·leetcode
lueluelue4716 小时前
LeetCode:滑动窗口
数据结构·算法·leetcode
Generalzy16 小时前
从本地 Demo 到生产级检索:Milvus 学习笔记(2)
golang·milvus
小高Baby@16 小时前
单链表的删操作
数据结构·算法·golang
青山木17 小时前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先
tachibana220 小时前
hot100 将有序数组转换为二叉搜索树(108)
java·数据结构·算法·leetcode
张32320 小时前
Go语言基础 Map 函数值 闭包
开发语言·golang