C++ recursive solution


  • 0
    G
    class Solution {
    public:
    
        template <typename I>
        bool CheckUTFMultiByte(I& begin, const I &end)
        {
            if(begin == end)
            {
                return (true);
            }
            
            if(((*begin) & (1 << 7)) != 0 &&
                ((*begin) & (1 << 6)) == 0)
                {
                    begin++;
                    return CheckUTFMultiByte(begin,end);
                }
                
            return (false);
        }
    
        template <typename I>
        bool validUtf8(I &begin, const I &end)
        {
            if(begin == end)
            {
                return true;
            }
            
            if(((*begin) & (1 << 7)) == 0)
            {
                begin++;
                return validUtf8(begin,end);
            }
            else
            {
                int Count = 0;
                int Mask = 7;
    
                while(((*begin) & (1 << Mask)) != 0)
                {
                    Count++;
                    
                    if(Count > 4)
                    {
                        return (false);
                    }
                    
                    Mask--;
                }
                
                if(Count == 1|| begin + Count >  end)
                {
                    return (false);
                }
                
                begin++;
                return (CheckUTFMultiByte(begin,begin + Count - 1) &&
                            validUtf8(begin,end));
                
            }
            
            return (false);
        }
    
        bool validUtf8(vector<int>& data) 
        {
          auto begin = data.begin();
          return validUtf8(begin,data.end());     
        }
    };

Log in to reply
 

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