LeetCode 393 - 编码验证

题目链接icon-default.png?t=M276https://leetcode-cn.com/problems/utf-8-validation/题目:

Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For a 1-byte character, the first bit is a 0, followed by its Unicode code.
For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.

This is how the UTF-8 encoding would work:   

Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

思路:

最开始的想法是把给定的整数转化为二进制数再进行判断。不过这一步很明显是多余的,其实直接整数利用位运算判断前几位的几个情况即可。注意边界条件的处理,在判断array[i+1]的时候需要先判断有没有数组越界!另外,循环变量的处理也需要注意:不能多也不能少加,continue之后会执行一次i++!

一开始想要转化为二进制却不知道从何下手,有空需要复习进制转化的有关知识。

题解:

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        int index=0, len=data.size();
        for(int i=0;i<len;i++){
            if(data[i]>>3==(2+4+8+16)){
                cout<<"find four bytes\n";
                if(i==len-1 || data[i+1]>>6!=2) return false;
                if(i==len-2 || data[i+2]>>6!=2) return false;
                if(i==len-3 || data[i+3]>>6!=2) return false;
                i+=3;
            }
            else if(data[i]>>4==(2+4+8)){
                cout<<"find three bytes\n";
                if(i==len-1 || data[i+1]>>6!=2) return false;
                if(i==len-2 || data[i+2]>>6!=2) return false;
                i+=2;
            }
            else if(data[i]>>5==(2+4)){
                cout<<"find two bytes\n";
                if(i==len-1 || data[i+1]>>6!=2) return false;
                i+=1;
            }
            else if(data[i]>>7==0) {
                cout<<"find one byte\n";
                continue;
            }
            else return false;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值