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 firstname.lastname@example.org. 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
- Queries to check if the path between two nodes in a tree is a palindrome
- Print shortest path to print a string on screen
- Range Sum and Update in Array : Segment Tree using Stack
- Maximum repeated frequency of characters in a given string
- Maximum number of strings that can be formed with given zeros and ones
- Maximum of XOR of first and second maximum of all subarrays
- Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
- Generate string with Hamming Distance as half of the hamming distance between strings A and B
- Longest suffix such that occurrence of each character is less than N after deleting atmost K characters
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Longest palindromic string possible after removal of a substring