Short'n'Clean 12-lines Python solution


  • 7
    def check(nums, start, size):
        for i in range(start + 1, start + size + 1):
            if i >= len(nums) or (nums[i] >> 6) != 0b10: return False
        return True
    
    class Solution(object):
        def validUtf8(self, nums, start=0):
            while start < len(nums):
                first = nums[start]
                if   (first >> 3) == 0b11110 and check(nums, start, 3): start += 4
                elif (first >> 4) == 0b1110  and check(nums, start, 2): start += 3
                elif (first >> 5) == 0b110   and check(nums, start, 1): start += 2
                elif (first >> 7) == 0:                                 start += 1
                else:                                                   return False
            return True
    
    # 45 / 45 test cases passed.
    # Status: Accepted
    # Runtime: 89 ms
    

  • -1
    V

    @agave I like your answer, but I think just for the sake of the question, your answer is not complete. The question requirement says:

    For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.

    With this definition, I think we should also check first >> 2, first >> 1 and first.

    Still, very clean solution.


Log in to reply
 

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