Golang | Leetcode Golang题解之第393题UTF-8编码验证

题目:

题解:

Go 复制代码
const mask1, mask2 = 1 << 7, 1<<7 | 1<<6

func getBytes(num int) int {
    if num&mask1 == 0 {
        return 1
    }
    n := 0
    for mask := mask1; num&mask != 0; mask >>= 1 {
        n++
        if n > 4 {
            return -1
        }
    }
    if n >= 2 {
        return n
    }
    return -1
}

func validUtf8(data []int) bool {
    for index, m := 0, len(data); index < m; {
        n := getBytes(data[index])
        if n < 0 || index+n > m {
            return false
        }
        for _, ch := range data[index+1 : index+n] {
            if ch&mask2 != mask1 {
                return false
            }
        }
        index += n
    }
    return true
}
相关推荐
JavaPub-rodert14 小时前
Go 后台如何同时兼容 MySQL、PostgreSQL、SQLite 和 SQL Server?从 ShiyuAdmin 看 GORM 多数据库适配
数据库·mysql·postgresql·golang·javapub·王仕宇
LuminousCPP18 小时前
栈和队列专题(四):LeetCode 232. 用栈实现队列|双栈分工 + 按需迁移 + 摊还 O(1)
c语言·数据结构·笔记·算法·leetcode
青 春 记 忆19 小时前
LeetCode 155. 最小栈|Python 解法详解
开发语言·python·leetcode
鹿角片ljp1 天前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
剩下了什么1 天前
float32 与 float64 精度陷阱:如何在 Go 中避免错误使用
开发语言·后端·golang
.道阻且长.1 天前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq71 天前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
青 春 记 忆1 天前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
小欣加油1 天前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
ttwuai1 天前
Go 后台接入 SSO 后菜单正常但接口 403,怎么排查权限链路?
开发语言·后端·golang