8ms Java solution


  • 0
    G
        public boolean validUtf8(int[] data) {
            if (data.length == 0) return false;
            int next = 0;
            for (int i = 0; i < data.length; i++) {
                if((data[i] & 0x80) == 0) {
                    if (next == 0) continue;
                    else return false;
                }
                
                if ((data[i] & 0xf8) == 0xf0) {
                    if (next != 0) return false;
                    next = 3;
                    continue;
                }
                
                if ((data[i] & 0xf0) == 0xe0) {
                    if (next != 0) return false;
                    next = 2;
                    continue;
                }
                
                if ((data[i] & 0xe0) == 0xc0) {
                    if (next != 0) return false;
                    next = 1;
                    continue;
                }
                
                if ((data[i] & 0xc0) == 0x80) {
                    if (next == 0) return false;
                    next--;
                    continue;
                }
                return false;
            }
            return next == 0;
        }
    

Log in to reply
 

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