Incorrect in spacing directories in Java

  • 0

    I followed the solution at here, almost the same but I got an incorrect result with spacing directories. I ran three cases, two first cases are good, but the method results in an incorrect number in the third case. The code is attached as below. Any helps would be appreciated.

    1st: "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
    2nd: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
    3rd: "dir\n\t file.txt\n\tfile2.txt"

    My answer: 20 32 44
    Expected answer: 20 32 43

    public class Solution {

     public int lengthLongestPath(String input) {
        int length=0, level=1, max1=0;
        boolean flag=false;
        HashMap<Integer, Integer> map = new HashMap<>();        
        for(int i=0; i< input.length(); ++i){
                ++level; ++i;
            while((input.charAt(i) != '\n') && (i < input.length()-1)){  
                if(input.charAt(i)=='.') flag=true;
                ++length; ++i;
            int lensum = 0;
                lensum = length + map.get(level-1);
            } else {
                lensum = length;
            while(input.charAt(i)==' '){ 
                ++length; ++i;
            if(flag==true) max1 = Math.max(max1, lensum+1); 
            else map.put(level, lensum+1); // +1 means '/'
        return max1;


Log in to reply

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