16ms C++, easy to understand!


  • 0
    X

    Some comments:
    1.Once we find the 7th digit(MSB) is 1, we start to verify.
    2.Two operations are needed. First, if pos==7, pos-- is used to count how many bytes in the following; Second, if pos!=7 we check the first two bits of the following bytes, and pos++ is used to determine we have verified the corresponding bytes.

    class Solution {
    public:
        bool validUtf8(vector<int>& data) {
            int pos=7;
            for(int i=0;i<data.size();i++){
                if(pos==7){
                    if(data[i]&(1<<pos)){
                        while(data[i]&(1<<pos))
                            pos--;
                        pos++;
                        if(pos==7) return false;//this is to avoid the case "10xxxxxx" 
                    }
                }else{
                    if(((data[i]&1<<7)==0)||((data[i]&1<<6)!=0))
                        return false;
                    pos++;
                }
            }
            return pos==7;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.