Java, O(n), one pass, 7ms, 11 lines


  • 0
    I
        public boolean validUtf8(int[] data) {
            for (int i = 0; i < data.length; ++i) {
                if ((data[i] & 128) == 0) continue; // 1 byte
                int mask = 64, count = 1;
                while (count <= 4 && (data[i] & mask) > 0) {
                    if (i + count >= data.length || data[i + count++] >>> 6 != 2) return false;
                    mask >>>= 1;
                }
                if (count < 2 || count > 4) return false;
                i += count - 1;
            }
            return true;
        }
    

Log in to reply
 

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