Java. String. Easy & Some Commends. Extensible. [4ms]


  • 2
    H
    public class Solution {
        public int lengthLongestPath(String input) {
            
            //split words
            String [] strs = input.split("\n");
            
            //save each folder name in a full path
            String [] path = new String[strs.length+1];
            int maxLength = 0;
            String maxPath = "";
            
            for(String str : strs){
                //check tab count. tab count means that deapth of the folder
                int tabCount = str.lastIndexOf("\t") + 1;
                
                //Get clear folder name by deleting \t from the str. 
                str=str.substring(tabCount, str.length());
                
                //If cur string is file
                if(str.contains(".")) {
                    //build full path 
                    String currentFullPath = "";
                    for(int i=0; i<tabCount; i++) currentFullPath+=path[i];
                    currentFullPath+=str;
                        
                    //update full path name. For extensibility purpose.
                    //currentFullPath.length() > maxLength ? maxPath=currentFullPath : ;
                
                    //update maxLength
                    maxLength = Math.max(maxLength, currentFullPath.length());
                
                }else path[tabCount] = str+"/";
                
            }
            
            return maxLength;
        }
    }
    

  • 1
    K

    u could have used stringbuilder to generate full paths to make it faster..


Log in to reply
 

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