Java solution, nested loop, O(n)


  • 0
    D
    public class Solution {
        public boolean validUtf8(int[] data) {
            if (data == null || data.length == 0) {
                return true;
            }
            int n = data.length;
            int p1 = 0;
            int p2 = 0;
            while (p1 < n) {
                int len = calcLen(data[p1]);
                if (len == -1) {
                    return false;
                }
                for (p2 = p1 + 1; p2 < n && p2 <= p1 + len - 1; p2++) {
                    if ((data[p2] & 0xC0) != 0x80) {
                        return false;
                    }
                }
                if (p2 == n && p2 != p1 + len) {
                    return false;
                }
                p1 = p2;
            }
            return true;
        }
        
        private int calcLen(int a) {
            if ((a & 0x80) == 0) {
                return 1;
            } else if ((a & 0xE0) == 0xC0) {
                return 2;
            } else if ((a & 0xF0) == 0xE0) {
                return 3;
            } else if ((a & 0xF8) == 0xF0) {
                return 4;
            } else {
                return -1;
            }
        }
    }
    

Log in to reply
 

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