Java Solution


  • 1

    Followings are the rules:
    1-byte: [0, 127]
    2-byte: [192, 223], [128, 191]
    3-byte: [224, 239], [128, 191], [128, 191]
    4-byte: [240, 247], [128, 191], [128, 191], [128, 191]
    5-byte: [248, 251], [128, 191], [128, 191], [128, 191], [128, 191]
    6-byte: [252, 254], [128, 191], [128, 191], [128, 191], [128, 191], [128, 191]
    7-byte: [255, 255], [128, 191], [128, 191], [128, 191], [128, 191], [128, 191], [128, 191]

    public class Solution {
        public boolean validUtf8(int[] data) {
            int index = 0, tailLen = 0;
            while(index < data.length) {
                tailLen = getTailLen(data[index]);
                
                // it is 1-byte character
                if(tailLen == 0) {
                    index++;
                    continue;
                }
                
                // the first 8-bit is invalid, or the tail is invalid
                if(tailLen == -1 || !isTailValid(data, index + 1, index + tailLen)) return false;
                index += tailLen + 1;
            }
            return true;
        }
        
        private int getTailLen(int num) {
            if(num <= 127) return 0;
            else if(num <= 191) return -1;
            else if(num <= 223) return 1;
            else if(num <= 239) return 2;
            else if(num <= 247) return 3;
            else if(num <= 251) return 4;
            else if(num <= 254) return 5;
            else return 6;
        }
        
        private boolean isTailValid(int[] data, int start, int end) {
            if(start >= data.length || end >= data.length) return false;
            for(int i = start; i <= end; i++) {
                if(data[i] < 128 || data[i] > 191) return false;
            }
            return true;
        }
    }
    

  • 0
    O

    Re: Java Solution
    0_1500435503029_7bd3c50d-7c9e-42d1-af6b-e052d4b00c05-image.png

    Actually, you don't need to return 4, 5, 6.
    Since the problem didn't ask >4 bytes, you can just mark them as -1. It will lead to correct result.

    0_1500435793354_118104a3-5367-4ea6-b82d-0d5e6d64e119-image.png


Log in to reply
 

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