Thursday, September 8, 2016

Leetcode 393 UTF-8 Validation Solution

Problem Statement could be found at following link

https://leetcode.com/problems/utf-8-validation/

Solution:


class Solution {
    private:
    const static int singleByteMask = 0x00000080;
    const static int multiByteFollower = 0x000000C0;
 
    const static int byte2Mask = 0x000000E0;
    const static int byte3Mask = 0x000000F0;
    const static int byte4Mask = 0x000000F8;
public:
    bool isSingleByte(int val){
           val = val & singleByteMask;
           return (val == 0);
    }
 
    bool isMultiByteFollower(int val){
        val = val & multiByteFollower;
           return (val == 128);
    }
    bool validUtf8(vector<int>& data) {
        int multiCharCount = 0;
        for (int index=data.size()-1;index>=0;index--){
            int num = data[index];
            if ( isSingleByte(num) == true){
                if (multiCharCount != 0)
                    return false;
            }else{
                if (isMultiByteFollower(num)){
                    multiCharCount++;
                    if (multiCharCount > 3)
                        return false;
                }else{
                    if (multiCharCount ==0)
                        return false;
                    else{
                        if (multiCharCount == 1){
                            num = byte2Mask & num;
                            if (num != 192){
                             
                                return false;
                            }else{
                                multiCharCount = 0;
                            }
                        }else if (multiCharCount == 2){
                             num = byte3Mask & num;
                             if (num != 224){
                               
                                return false;
                             }else{
                                multiCharCount = 0;
                             }
                        }else if (multiCharCount == 3){
                            num = byte4Mask & num;
                             if (num != 240){
                               
                                return false;
                             }else{
                                multiCharCount = 0;
                             }
                        }
                    }
                }
             
            }
        }
        return (multiCharCount ==0) ;
    }
};

No comments:

Post a Comment