c++ iterative solution


  • 0
    W
    class Solution {
    	bool isBitZero(int i, int idx)
    	{
    		return ((i >> idx) & 1) == 0;
    	}
    	int countBit(int i) 
    	{
    		if (isBitZero(i, 7)) return 0;
    		if (isBitZero(i, 6)) return -1; // invalid
    		if (isBitZero(i, 5)) return 2;
    		if (isBitZero(i, 4)) return 3;
    		if (isBitZero(i, 3)) return 4;
    		return -1; // invalid
    	}
    	bool byteValid(int b) 
    	{
    		return (b & 128) && isBitZero(b, 6);
    	}
    public:
    	bool validUtf8(vector<int>& data) 
    	{
    		int i = 0;
    		while (i < data.size())
    		{
    			int byte = data[i];
    			int cnt = countBit(byte);
    			if (cnt == -1)
    			{
    				return false;
    			}
    			if (cnt == 0) 
    			{
    				i += 1; 
    				continue;
    			}
    			for (int j = 1; j <= cnt - 1; j++)
    			{
    				if (i + j >= data.size())
    				{
    					return false;
    				}
    				if (!byteValid(data[i + j]))
    				{
    					return false;
    				}
    			}
    			i += cnt;
    		}
    		return true;
    	}
    };
    

Log in to reply
 

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