Simple Solution in Java,beats 43.51%


  • 0

    First define a array level[n],then split the input by "\n".And we will get n string.Each string present a level in the dictionary.Now we should know the level of current level.For example "\t\tabc",there is two "\n" in the string.So we can know it is the 2th level.The current path is level[n-1]+"\n"+level[n].

    class Solution {
        public int lengthLongestPath(String input) {
            String[]pathArr=input.split("\n");
            String[]level=new String[input.length()];
            int maxLength=0;
            String maxPath="";
            for(String str:pathArr){
                int count=countTab(str);
                if(count==0){
                    level[0]=str;
                }else{
                    level[count]=level[count-1].substring(count,level[count-1].length())+"\\"+str;
                }
                if(str.contains(".")&&level[count].length()>maxLength){
                    maxLength=level[count].length();
                    maxPath=level[count];
                }
            }
            return maxLength;
        }
        public int countTab(String str){
            int count=0;
            for(int i=0;i<str.length()-1;i++){
                if(str.charAt(i)=='\t'){
                    count++;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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