C++ solution


  • 0
    Z
    class Solution {
    public:
    
        bool isFile(string str){
            std::size_t found=str.find('.');
            if(found != std::string::npos) return true;
            else return false;
        }
        
        int lengthLongestPath(string input) {
            
            int strLen=input.size();
            if(strLen==0) return 0;
            
            int longestPath=0;
            int path;
            
            vector<int> len_of_levels;
            len_of_levels.push_back(0);
            
            string filename;
            int level;
            
            for(int i=0; i<strLen; i++){
                
                level=0;
                filename="";
                //find level
                while(input[i]=='\t'){
                    level++;
                    i++;
                }
                //read string
                while(input[i]!='\n' && i<strLen){
                    filename=filename+input[i];
                    i++;
                }
                //store the path to the current string
                while(len_of_levels.size()>level){
                    len_of_levels.pop_back();
                }
                
                len_of_levels.push_back(filename.size());
                //check whether a file is reached and calculate its length
                if(isFile(filename)){
                    path=0;
                    for(int j=0; j<len_of_levels.size(); j++){
                        path=path+len_of_levels[j];
                    }
                    if(path+len_of_levels.size()-1>longestPath) longestPath=path+len_of_levels.size()-1;
                }
                
            }
            
            return longestPath;
            
        }
    };
    

Log in to reply
 

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