Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Count Directories

Sharing is caring!

Problem Statement
Given a directory change command cd a/b/../c/d/e/../../ output the visit count of each directory such as: {a=2, b=1, c=2, d=2, e=1}.
Solution
package problems;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class CountDirectory {

    private static Map<String, Integer> count(String path) {
        String[] dirs = path.split("/");
        Stack<String> stack = new Stack<>();
        Map<String, Integer> count = new HashMap<>();

        for (String d:dirs) {
            String dir = d;
            if ("..".equals(dir)) {
                stack.pop();
                dir = stack.peek();
            } else {
                stack.add(dir);
                if (!count.containsKey(dir)) {
                    count.put(dir, 0);
                }
            }

            count.put(dir, count.get(dir) + 1);
        }

        return count;
    }

    public static void main(String[] args) {
        String path = "a/b/../c/d/e/../../";
        System.out.println(count(path));
    }
}