Skip to content
LC-0393 Medium LeetCode

393. UTF-8 Validation

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 45% Topics: Array, Bit Manipulation
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class Solution(object):
    def validUtf8(self, data):
        """
        :type data: List[int]
        :rtype: bool
        """
        count = 0
        for c in data:
            if count == 0:
                if (c >> 5) == 0b110:
                    count = 1
                elif (c >> 4) == 0b1110:
                    count = 2
                elif (c >> 3) == 0b11110:
                    count = 3
                elif (c >> 7):
                    return False
            else:
                if (c >> 6) != 0b10:
                    return False
                count -= 1
        return count == 0

Solution from kamyu104/LeetCode-Solutions · MIT