Easy to follow and well structured stack solution (C++)


  • 0
    G
    class Solution {
    public:
    
        struct StackStruct
        {
            int Len;
            int Dep;
            bool IsFile;
        };
    
        void HandleStr(vector<StackStruct> &S,const string &Str,int &Max)
        {
            int i = 0;
            while(i < Str.size() && Str[i] == '\t')
            {
                i++;
            }
            
            StackStruct SS;
            SS.Dep = i;
            SS.Len = Str.size() - i;
            SS.IsFile = (Str.find('.') != string::npos);
            
            while(S.empty() == false && S.back().Dep >= SS.Dep)
            {
                if(S.back().IsFile)
                {
                    Max = max(Max,S.back().Len);
                }
                
                S.pop_back();
            }
            
            if(S.empty() == false)
            {
                SS.Len += S.back().Len + 1;
            }
            
            S.push_back(SS);
        }
    
        int lengthLongestPath(string input) 
        {
            
            int Max = 0;
            
            vector<StackStruct> Stack;
            
            istringstream ss(input);
            string Temp;
            
            while(getline(ss,Temp,'\n'))
            {
                HandleStr(Stack,Temp,Max);
            }
            
            if(Stack.empty() == false)
            {
                if(Stack.back().IsFile)
                {
                    Max = max(Max,Stack.back().Len);
                }
            }
            
            return (Max);
        }
    };
    

Log in to reply
 

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