Java 10 ms solution using bit operation.


  • 0

    Using bit operation to check size and validation.

    public class Solution {
        int getLen(int bt){
            int mask = 0x0080;
            if ((bt & mask) == 0) return 0; //check first bit is 1 or 0
            mask >>= 1;
            if ((bt & mask) == 0) return -1; //check the second bit, if 0 return -1
             mask >>= 1;
            int len = 1; // using while loop to find the size
            while ( (mask != 0) && ( (bt & mask) == mask) ) {
                mask >>= 1;
                len++;
            }
            return len==7? -1: len; // the case of 11111111, return -1.
        }
        
        public boolean validUtf8(int[] data) {
            if (data == null || data.length ==0) return false;
            int i=0;
            while (i < data.length) {
                int len = getLen(data[i]); // get the size from the header byte
                if ((len < 0) || (i+len) >= data.length ) return false; // not a validate header byte or there is a shortage on the length
                while ( len > 0) { // check the data bytes
                    if ( (data[++i] >> 6) != 2) return false; // check 10xxxxxx
                    len--;
                }
                if (len > 0) return false;  // shortage on the length
                i++;
            }
            return true;
        }
    }
    

Log in to reply
 

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