Readable python solution


  • 0
    E
    def get_char_byte_num(btext):
        if btext[0] == '0':
            return 0
        return btext.find('0')-1
    
    def validate_leading_byte(btext):
        if btext[:2] == '10':
            return False
        if btext.find('0') == -1 or btext.find('0') > 4:
            return False
        return True
    
    def validate_typical_byte(btext):
        return btext[:2] == '10'
    
    def to_bin(x):
        bin_text = '{:b}'.format(x)
        diff = (8-len(bin_text))
        if diff < 0:
            diff = 0
        bin_text = diff*'0'+bin_text
        return bin_text
        
    class Solution(object):
        def validUtf8(self, data):
            """
            :type data: List[int]
            :rtype: bool
            """
            if not data:
                return False
            bdata = [to_bin(x) for x in data ] 
            i=0
            #print(bdata)
            while i < len(bdata):
                byte = bdata[i]
                if not validate_leading_byte(byte):
                    return False
                bytes_ahead = get_char_byte_num(byte)
                #print(byte, 'byte')
                #print(bytes_ahead, 'ahead')
                if bytes_ahead > 0:
                    for j in range(1, bytes_ahead+1):
                        if i+j >= len(bdata):
                            return False
                        if not validate_typical_byte(bdata[i+j]):
                            return False
                    i = i+bytes_ahead+1
                else:
                    i = i +1
            
            return True
    

Log in to reply
 

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