Simple one pass concise Java solution beating 99%


  • 2

    So, I wrote a literal translation of the problem statement in Java. This works in O(n), obviously.

    public class Solution {
    	public boolean validUtf8(int[] data) {
    		int varCharLeft = 0;
    		for (int b: data) {
    			if (varCharLeft == 0) {
    				if ((b & 0b010000000) == 0)  varCharLeft = 0;
    				else if ((b & 0b011100000) == 0b11000000)  varCharLeft = 1;
    				else if ((b & 0b011110000) == 0b11100000)  varCharLeft = 2;
    				else if ((b & 0b011111000) == 0b11110000)  varCharLeft = 3;
    				else return false;
    			} else {
    				if ((b & 0b011000000) != 0b10000000)  return false;
    				varCharLeft--;
    			}
    		}
    		return varCharLeft==0;
    	}
    }
    

    Just bragging, this beats 99.86% submissions. But, seems like in leetcode, timing is very inconsistent nowadays.
    0_1475701198342_Capture.PNG


  • 0
    S

    great solution!
    but I was trying to use 8-bit to check instead of 9-bit with extra '0' at the left most significant bit, but it failed. can you pelase tell me the teason?


  • 0
    S

    @syjohnson I see... the 9th bit with number 'b' could be 1


Log in to reply
 

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