C++ A accepted naive algorithm.


  • 0
    L

    beats 82.55%.

    class Solution {
    public:
        bool validUtf8(vector<int>& data) {
            int count = 0;
            int n = data.size();
            while (count < n)
        	{
        		int pre_count = count;
        		if (count + 1 <= n && (data[count] & 0x00000080) == 0) {
        			count++;
        		}
        		else if (count + 2 <= n && ((data[count] & 0x000000E0) >> 5 == 6) && (((data[count+1] & 0x000000C0) >> 6) == 2)) {
        			count += 2;
        		}
        		else if (count + 3 <= n && ((data[count] & 0x000000F0) >> 4 == 14) && (((data[count+1] & 0x000000C0) >> 6) == 2 && ((data[count+2] & 0x000000C0) >> 6) == 2)) {
        			count += 3;
        		}
        		else if (count+4 <= n && ((data[count] & 0x000000F8) >> 3 == 30) && (((data[count+1] & 0x000000C0) >> 6) == 2 && ((data[count+2] & 0x000000C0) >> 6) == 2 && ((data[count+3] & 0x000000C0) >> 6) == 2)) {
        			count+=4;
        			continue;
        		}
        		if (pre_count == count) {
        			return false;
        		}
        	}
        	
        	return true;
        }
    };
    

  • 0
    L

    In fact, 0x00000080== 0x080 . I can use data[count] & 0x080) == 0 , instead.


Log in to reply
 

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