Ruby solution using single pass


  • 0
    T
    # @param {Integer[]} data
    # @return {Boolean}
    def valid_utf8(data)
      counter = 0
      data.each do |byte|
        binary_str = byte.to_s(2)
        while(binary_str.length < 8) do
          binary_str = "0" + binary_str
        end
        if counter == 0 && binary_str[0] == "1"
          i = 1
          while(binary_str[i] == "1") do
            i += 1
          end
          return false if i == 1
          counter = i - 1
        elsif counter != 0
          return false if binary_str[0..1] != "10"
          counter -= 1
        elsif counter == 0 && binary_str[0] != "0"
          return false
        end
      end
      return false if counter != 0
      return true
    end
    ````

Log in to reply
 

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