Given an absolute path for a file (Unix-style), simplify it. Note that absolute path always begin with ‘/’ ( root directory ), a dot in path represent current directory and double dot represents parent directory.
"/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 : /home/ Output : /home Input : /a/./b/../../c/ Output : /c Input : /a/.. Output:/ Input : /a/../ Output : / Input : /../../../../../a Output : /a Input : /a/./b/./c/./d/ Output : /a/b/c/d Input : /a/../.././../../. Output:/ Input : /a//b//c//////d Output : /a/b/c/d
By looking at examples we can see that the above simplification process just behaves like a stack. Whenever we encounter any file’s name, we simply push it into the stack. when we come across ” . ” we do nothing. When we find “..” in our path, we simply pop the topmost element as we have to jump back to parent’s directory.
When we see multiple “////” we just ignore them as they are equivalent to one single “/”. After iterating through the whole string the elements remaining in the stack is our simplified absolute path. We have to create another stack to reverse the elements stored inside the original stack and then store the result inside a string.
Time Complexity O(length of string).
This article is contributed by arshpreet soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program for longest common directory path
- Shortest Path using Meet In The Middle
- Minimum number of stops from given path
- Print shortest path to print a string on screen
- Count number of substrings of a string consisting of same characters
- Concatenate the strings in an order which maximises the occurrence of subsequence "ab"
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- Print characters having prime frequencies in order of occurrence
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket
- Longest substring such that no three consecutive characters are same
- Find the winner of the game
- Print characters having even frequencies in order of occurrence
- Compare two strings considering only alphanumeric characters
- Minimum given operations required to convert a given binary string to all 1's