11/07/2021

[Java] Simplify unix path

Given a string representing a unix path, simplify it to remove dots and repeated slashes, condensing only to the folders appearing in the final path.

Example:

/../ return / as we can't move up from root

/asd/../lol return /lol as we went into asd, then moved out from it

We can do this in O(N) time and space by using a queue.

We first split the string over the "/" character to separate all folders and special characters.

If there are repeated slashes together (eg "//") the split would return an empty string for them.

We then loop over all strings in the split and check the following cases:

  • encounter a single dot "." or an empty string "": we skip this as the dot means "stay in this folder" and the empty string means we had consecutive slashes
  • encounter a double dot "..": if the queue is not empty, we remove from the tail the last folder we added as we just moved out of it
  • in all other cases, we have a folder name, we add it to our queue

Then, we can recreate the path by appending all elements in the queue together

This won't be O(N^2) since removing from the queue at most will make us walk the whole string twice (we can't remove more than we add).

You can check my implementation of simplifyPath on my Gist along with some tests in SimplifyPathJTests.

No comments:

Post a Comment

With great power comes great responsibility