Clean Java 8 Solution using Stream


  • 0
    M
    public int lengthLongestPath(String input) {
        
        // corner cases
        if (input == null || input.length() == 0)
            return 0;
        
        // init
        String[] objects = input.split("\n");
        List<String> levels = new ArrayList<>();
        int max = 0;
        
        for (int i = 0; i < objects.length; i++) {
            
        	// add object into the path
            int numOfT = getNumberOfT(objects[i]);
            
            String cleanObject = objects[i].replaceAll("\t", "");
            
            if (levels.size() <= numOfT)
            	levels.add(cleanObject);
            else
            	levels.set(numOfT, cleanObject);
            
            if (isFile(cleanObject)) {
                int length = getLength(levels, numOfT);
                if (length > max)
                    max = length;
            }
            
        }
        
        return max;
    }
    
    private int getNumberOfT(String object) {
        long occurances = object
                           .chars()
                           .filter(c -> c == '\t')
                           .count();
        return (int) occurances;
    }
    
    private boolean isFile(String object) {
        return object.contains(".");
    }
    
    // returns the length of the path from root -> specific depth
    private int getLength(List<String> levels, int depth) {
        return levels.stream()
                 .limit(depth + 1)
                 .reduce(0, 
                		 (totalLength, object) -> totalLength += object.length(), 
                		 (t1, t2) -> t1 + t2) + depth;
        // + depth because we need to count / separating each object
    }

Log in to reply
 

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