Skip to main content

Command Palette

Search for a command to run...

Leetcode 71 Simplify Path

Updated
•1 min read•View as Markdown

Approach

The idea is to get rid of unnecessary tokens from the path. Three types of tokens can be cleaned.

The empty token "//" --> "/".

"." token: /a/./b" -> "/a/b"

".." token : "/a/../b" -> "b".

Algorithm

  1. Split the path into tokens separated by the "/" character.

  2. Keep track of subdirectories in a stack data structure.

  3. If a token is neither "." nor "..", it could be part of the simplified path, so push it onto the stack. If the token is "..", remove the top subdirectory from the stack if it is non-empty. Ignore "." tokens.

  4. Join the subdirectories present in the stack with the "/" character to form the simplified path.

    public String simplifyPath(String path) {

        String DELIMITER = "/";
        var tokens = path.split(DELIMITER);

        var stack = new Stack<String>();

        for (var token : tokens) {
            if (token.length() != 0) {
                if (!token.equals(".") && !token.equals(".."))
                    stack.push(token);
                else if (token.equals("..") && !stack.empty())
                    stack.pop();
            }
        }

        return DELIMITER + String.join(DELIMITER , stack);
    }