Given a string path, which is an absolute path (starting with a slash ‘/’) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
“/a/./” –> means stay at the current directory ‘a’
“/a/b/..” –> means jump to the parent directory from ‘b’ to ‘a’
”////” –> consecutive multiple ‘/’ are a valid path, they are equivalent to single “/”.
Input | Output |
---|---|
/home/ | /home |
/a/./b/../../c/ | /c |
/a/.. | / |
/a/../ | / |
/../../../../../a | /a |
/a/./b/./c/./d/ | /a/b/c/d |
/a/../.././../../. | / |
/a//b//c//////d | /a/b/c/d |
Time Complexity - O(n) | Space Complexity - O(n)
class Solution {
public String simplifyPath(String path) {
StringBuilder builder = new StringBuilder();
Stack<String> stack = new Stack<>();
String[] components = path.split("/");
for (String dir : components) {
if (dir.equals(".") || dir.isEmpty()) {
continue;
} else if (dir.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.add(dir);
}
}
for (String dir : stack) {
builder.append("/");
builder.append(dir);
}
return builder.length() > 0 ? builder.toString() : "/";
}
}
| Custom Sort String | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. Return any permutation...
read more