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 == '?'
}
相关推荐
Villiam_AY35 分钟前
goredis常见基础命令
redis·golang
PyAIGCMaster35 分钟前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
PyAIGCMaster38 分钟前
第二周补充:Go语言中&取地址符与fmt函数详解
开发语言·后端·golang
闲猫7 小时前
go orm GORM
开发语言·后端·golang
丁卯4047 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
Dream it possible!10 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉10 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生10 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴10 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing10 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode