C++ 0ms solution


  • 0
    F
        int lengthLongestPath(string input) {
            int preLen=0;
            int maxLen=0;
            vector<int> dirLen;
            dirLen.push_back(0);
            const char *p = input.c_str();
            while(*p != 0) {
                //next token
                int numPreDir = 0;
                while(*p == '\t') {
                    ++numPreDir;
                    ++p;
                }
                int tokenLen = 0; 
                bool isFile = false;
                while(*p != '\n' && *p != 0) {
                    ++tokenLen;
                    if(*p == '.') isFile = true;
                    ++p;
                }
                
                if(isFile) {
                    maxLen = max(maxLen, dirLen[numPreDir]+ numPreDir + tokenLen);
                }else{
                    //directory
                    if(numPreDir == dirLen.size()-1) 
                        dirLen.push_back(dirLen.back() + tokenLen);
                    else
                        dirLen[numPreDir+1] = dirLen[numPreDir] + tokenLen;
                }
                if(*p == '\n') ++p;    // skip '\n'
            }
            return maxLen;
        }

Log in to reply
 

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