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 == '?'
}
相关推荐
吃着火锅x唱着歌4 小时前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
元亓亓亓7 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香7 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法7 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油7 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实7 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
周杰伦_Jay8 小时前
【主流开发语言深度对比】Python/Go/Java/JS/Rust/C++评测
开发语言·python·golang
ldmd2848 小时前
Go语言实战:入门篇-5:函数、服务接口和Swagger UI
开发语言·后端·golang
im_AMBER10 小时前
算法笔记 10
笔记·学习·算法·leetcode
NPE~10 小时前
[手写系列]Go手写db — — 第七版(实现Disk存储引擎、Docker化支持)
数据库·后端·docker·golang·教程·手写数据库