Simplify Path
Clean up a Unix file path by removing extra slashes, single dots and the steps that go back up.
On Unix systems such as Linux and macOS, the place of a file is written as a path like /home/foo
Given an absolute path as a string path
means the current directory, so it changes nothing and is dropped;"." means the parent directory, one level up; at the root it does nothing;".."- several slashes in a row count as one;
- any other name, including
, is an ordinary directory name."..."
The simplified form starts with a single slash, separates directory names with single slashes, and has no slash at the end.
Example 1
Output: "/home"
Example 2
Output: "/"
Example 3
Output: "/home/foo"
Example 4
Output: "/c"
The Idea
If you have used a terminal, you have probably typed cd .."/a/./b/../../c/"abc/c
The single dots and the extra slashes are easy, because they never move you anywhere. The real question is the ".."
Always the one you entered most recently and have not left yet. The first ".."bab
The row labelled "part" holds the pieces between the slashes, read left to right. The first piece is empty, because nothing comes before the first slash. Below each part, the row labelled "action" says what it does, and the bottom row, labelled "directories we are inside", shows where we are after it.
Follow the bottom row. aba".."bacc/c
A pile where you only ever add to the top and take from the top is called a stack. Adding is called push and taking the top away is called pop. A directory name is pushed, and each ".."
Solution Approach
Turning that idea into code means settling three things: how to break the path into parts, what each part does to the stack, and how to build the simplified path from what is left on it.
Breaking the path into parts
How do we get the parts out of the string? Java's String.split("/")split
So every extra slash turns into an empty string, and skipping empty strings is all it takes to treat several slashes as one.
What each part does to the stack
Which parts change the stack? Empty parts and ".""..""..."
Building the simplified path
Which order should the names come out in? The bottom of the stack holds the outermost directory, so the path is written from the bottom up, each name with a slash before it. If the stack is empty, the answer is the root, "/"
A plain stack only lets us take from the top, which would give the names backwards. Java's ArrayDequepushpoppollLast
Java Solution
The method simplifyPath
- First, create the stack,
, as andirs . It holds the directories we are inside.ArrayDeque<String> - Split
withpath , and loop over the pieces, calling each onepath.split("/") .part - If
is empty orpart , skip it with"." .continue - If
ispart , pop the top name from".." , but only whendirs is not empty.dirs - Otherwise
is a directory name, so push it ontopart .dirs - After the loop, build the answer in a
namedStringBuilder . A second loop takes names from the bottom ofresult withdirs and appends each one after a slash.pollLast() - Return
if"/" is still empty, and the text inresult otherwise.result
The main"..""..."
import java.util.ArrayDeque;
import java.util.Deque;
public class SimplifyPath {
public static String simplifyPath(String path) {
Deque<String> dirs = new ArrayDeque<>();
for (String part : path.split("/")) {
if (part.isEmpty() || part.equals(".")) {
continue; // from "//" or "."
}
if (part.equals("..")) {
if (!dirs.isEmpty()) {
dirs.pop(); // go up one level; at the root nothing happens
}
} else {
dirs.push(part);
}
}
StringBuilder result = new StringBuilder();
while (!dirs.isEmpty()) {
result.append('/').append(dirs.pollLast()); // bottom of the stack first
}
return result.length() == 0 ? "/" : result.toString();
}
public static void main(String[] args) {
String[] paths = {
"/home/", "/../", "/home//foo/", "/a/./b/../../c/",
"/a/../../b", "/...", "/a//b////c/d//././/..", "/"
};
for (String path : paths) {
System.out.println(path + " -> " + simplifyPath(path));
}
}
}
Running it prints:
/home/ -> /home
/../ -> /
/home//foo/ -> /home/foo
/a/./b/../../c/ -> /c
/a/../../b -> /b
/... -> /...
/a//b////c/d//././/.. -> /a/b/c
/ -> /
Each line shows a path, an arrow, and its simplified form. Look at /a/../../b -> /b".."acd ..b
The line /... -> /.../a//b////c/d//././/.. -> /a/b/c".."d
The isEmpty()pop()ArrayDeque.pop()"/../"java.util.NoSuchElementException/
The original implementation,
Complexity
The work is one split of the path, one push or pop per part, and one pass to write the answer.
- Time: O(n) for a path of n characters.
reads each character once, each name is pushed at most once and popped at most once, and the final loop writes at most n characters.split - Space: O(n). The array of parts from
and the names on the stack are pieces of the path, so together they hold at most its n characters.split
The same "push, then pop on a step back" idea solves