Simplify the Directory
Posted: 25 Aug, 2020
Difficulty: Moderate
You are given a path to a file/directory in Unix-style of length N, In a Unix-style file system, a dot(.) refers to the current directory. A double dot(..) refers to the previous directory in reference to the current directory. If there are multiple slashes between two directories you should consider it as a single slash.
Now, for a given directory path as a string, you are required to simplify the same and tell the final destination in the directory structure or the path.
The simplified path should always begin with a slash(/) and there must be a single slash between two directory names. There should not be a trailing slash.
Input Format :
The first line contains an integer T which denotes the number of test cases to be run.
The first and only line of each testcase contains a single string denoting the path .
Output Format:
For each test case, print a string representing a simplified path to the resulting file or directory.
Note:
You are not required to print anything explicitly. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100
0 <= N <= 10^5
Where N is the length of the input path.
Time Limit : 1 sec
Approach 1
- Initialize a stack that will store the directories.
- For every directory between slashes check
a). If it is a dot then continue.
b). If it is double dot then pop the directory from the stack.
c). Else push into the stack.
- Now, take an empty string and a temporary stack.
- Pop all the elements from the first stack and store into a temporary stack.
- Pop all the elements from the temporary stack and store into an answer string and add a slash.
- Return the answer string.
SIMILAR PROBLEMS
Prime Digit Sum
Posted: 17 Apr, 2022
Difficulty: Hard
Count Numbers Containing Given Digit K Times
Posted: 20 Apr, 2022
Difficulty: Moderate
Count Numbers With Equal First and Last Digit
Posted: 20 Apr, 2022
Difficulty: Moderate
Max Non Adjacent sum
Posted: 10 May, 2022
Difficulty: Easy
Mario And His Princess
Posted: 12 May, 2022
Difficulty: Moderate