C++ 19ms short solution with comments


  • 0
    bool validUtf8(vector<int>& data) {
            int mask1 = 128, mask2 = 192, cnt = 0;
            
            for (int i = 0; i < data.size(); i++) {
                int cur = data[i];
                
                if (cnt == 0) {                                         // count leading 1s
                    while ((cur & mask1) != 0) {
                        cur <<= 1;
                        cnt++;
                    }
                    if (cnt == 1) { return false; }                     // cnt cannot be 1
                    cnt = max(0, cnt - 1);                              // decrease cnt by 1 if cnt > 1
                } else {                            
                    if ((data[i] & mask2) != mask1) { return false; }   // make sure most significant 2 bits are 10
                    cnt--;
                }
            }
            
            return cnt == 0;
        }
    

Log in to reply
 

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