Simple C++ solution with comment inside


  • 0
    class Solution {
    public:
        int lengthLongestPath(string input) {
            int maxLen = 0; 
            stack<pair<int,int>> stk;
                // stk.top().first => tab level,
                // stk.top().second => length record
            
            string str;
            istringstream iss(input);
            while(getline(iss,str)){
                int cur = 0; // The 'current tab level'
                while(str[cur++]=='\t' );
                int len = str.size()-cur+1; // The length.
                
                if(!stk.empty())
                while(cur <= stk.top().first) { //Free stk if the 'current tab level' <= the top one
                    stk.pop();;
                    if(stk.empty()) break;
                }
                stk.push( {cur, stk.empty() ? len : stk.top().second+len+1} ); // +1 to include the '/' length.
                
                if( str.find(".") != -1 )maxLen = max(maxLen, stk.top().second);
            }
            return maxLen;
        }
    };
    

Log in to reply
 

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