One pass and straightForward java solution


  • 0
    F
        public boolean validUtf8(int[] data) {
            int n = data.length;
            for (int i = 0; i < n; i++) {
                if ((data[i] & 0x80) != 0) {
                    if ((data[i] & 0xe0) == 0xc0) {
                        if (i + 1 >= n
                                || (data[i + 1] & 0xc0) != 0x80) {
                            return false;
                        }
                        i += 1;
                    } else if ((data[i] & 0xf0) == 0xe0) {
                        if (i + 2 >= n
                                || (data[i + 1] & 0xc0) != 0x80
                                || (data[i + 2] & 0xc0) != 0x80) {
                            return false;
                        }
                        i += 2;
                    } else if ((data[i] & 0xf8) == 0xf0) {
                        if (i + 3 >= n
                                || (data[i + 1] & 0xc0) != 0x80
                                || (data[i + 2] & 0xc0) != 0x80
                                || (data[i + 3] & 0xc0) != 0x80) {
                            return false;
                        }
                        i += 3;
                    } else {
                        return false;
                    }
                }
            }
            return true;
        }

Log in to reply
 

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