C++ | Leetcode C++题解之第393题UFT-8编码验证

题目:

题解:

cpp 复制代码
class Solution {
public:
    static const int MASK1 = 1 << 7;
    static const int MASK2 = (1 << 7) + (1 << 6);

    bool isValid(int num) {
        return (num & MASK2) == MASK1;
    }

    int getBytes(int num) {
        if ((num & MASK1) == 0) {
            return 1;
        }
        int n = 0;
        int mask = MASK1;
        while ((num & mask) != 0) {
            n++;
            if (n > 4) {
                return -1;
            }
            mask >>= 1;
        }
        return n >= 2 ? n : -1;
    }

    bool validUtf8(vector<int>& data) {
        int m = data.size();
        int index = 0;
        while (index < m) {
            int num = data[index];
            int n = getBytes(num);
            if (n < 0 || index + n > m) {
                return false;
            }
            for (int i = 1; i < n; i++) {
                if (!isValid(data[index + i])) {
                    return false;
                }
            }
            index += n;
        }
        return true;
    }
};
相关推荐
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Lucis__5 小时前
再探类&对象——C++入门进阶
开发语言·c++
北京不会遇到西雅图6 小时前
【SLAM】【后端优化】不同优化方法对比
c++·机器人
jndingxin6 小时前
c++多线程(6)------ 条件变量
开发语言·c++
程序员莫小特6 小时前
老题新解|大整数加法
数据结构·c++·算法
zycoder.8 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!8 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
洲覆8 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
学学学无无止境9 小时前
组合两个表-力扣
leetcode