Simple Javascript solution

  • 0
    var lengthLongestPath = function(input) {
         var lines = input.split("\n");
         var inputArray = [0];
         var maxLen = 0;
              var line = lines[i];
             //The depth can be calculated using number of tabs 
             var depth = line.lastIndexOf("\t")+1;
            //We want to pop from stack until we're are the correct depth
            //trim the tabs in the start of the line
            line = line.substring(line.lastIndexOf("\t")+1);
            if(line.includes(".")){             //this is a file
                 //no "/" is expected at the end of a file. 
                 var curLen = line.length+inputArray[inputArray.length-1];
                 if(curLen > maxLen){
                     maxLen = curLen;
             } else {
                 //this is a folder
                 var curLen = line.length+1+inputArray[inputArray.length-1];
                 //update the stack with length from start all the way to current folder
         return maxLen; 

  • 0

    when the input don't "\t" , example "mydir\n file.txt", the result is wrong.

Log in to reply

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