LeetCode 393: UTF-8 Validation Solution

Master LeetCode problem 393 (UTF-8 Validation), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

393. UTF-8 Validation

Problem Explanation

Explanation:

To validate if the given data is a valid UTF-8 encoding, we need to check if it follows the given rules for UTF-8 encoding. We iterate over the given data array, check each byte to determine the number of bytes in the character it represents, and verify if the subsequent bytes are continuation bytes (start with "10"). If all bytes follow the rules, we return true; otherwise, we return false.

Detailed steps:

  1. Iterate over the data array.
  2. Determine the number of bytes in the current character based on the first few bits.
  3. Check if the subsequent bytes are continuation bytes.
  4. Repeat the process for each character.
  5. Return true if all characters are valid UTF-8 encoded, false otherwise.

Time complexity: O(n), where n is the length of the data array. Space complexity: O(1) as we use constant extra space.

Solution Code

class Solution {
    public boolean validUtf8(int[] data) {
        int count = 0;
        for (int d : data) {
            if (count == 0) {
                if ((d >> 5) == 0b110) count = 1;
                else if ((d >> 4) == 0b1110) count = 2;
                else if ((d >> 3) == 0b11110) count = 3;
                else if ((d >> 7) == 0b1) return false;
            } else {
                if ((d >> 6) != 0b10) return false;
                count--;
            }
        }
        return count == 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 393 (UTF-8 Validation)?

This page provides optimized solutions for LeetCode problem 393 (UTF-8 Validation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 393 (UTF-8 Validation)?

The time complexity for LeetCode 393 (UTF-8 Validation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 393 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 393 in Java, C++, or Python.

Back to LeetCode Solutions