Simplify Path — Leetcode
Topic: String
Difficulty: Medium
Implementing using Stack.
Problem Statement:
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.
In a Unix-style file system, a period '.'
refers to the current directory, a double period '..'
refers to the directory up a level, and any multiple consecutive slashes (i.e. '//'
) are treated as a single slash '/'
. For this problem, any other format of periods such as '...'
are treated as file/directory names.
The canonical path should have the following format:
- The path starts with a single slash
'/'
. - Any two directories are separated by a single slash
'/'
. - The path does not end with a trailing
'/'
. - The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period
'.'
or double period'..'
)
Return the simplified canonical path.
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are
replaced by a single one.
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the
root level is the highest level you can go.
Explanation:
This problem is very common for those who have been working on terminals, Linux or etc.
As the canonical path formatting is been given above, so let's dive into the dry run of the question.
If a string given is: ‘/abc/..’
The output will be: ‘/’
(note: here, ‘..’ will only contain the directories on the path from the root directory to the target file or directory, therefore abc directory will be removed)
Code:
java
class Solution {
public String simplifyPath(String path) {
String token[] = path.split("/");
Stack<String> stack = new Stack();
for(int i = 0; i < token.length ; i++){
if(token[i].length()>0){
if(token[i] .equals( ".")) continue;
if(token[i] .equals( "..")){
if(!stack.isEmpty()){
stack.pop();
}
continue;
}
stack.push(token[i]);
}
}
String ans = "/";
if(stack.isEmpty()){
return ans;
}
ans = "";
for(String s: stack){
ans +="/";
ans += s;
}
return ans;
}
}
python by Vaishnav Jha
class Solution:
def simplifyPath(self, path: str) -> str:
direc = path.split('/') # Making array from string
ans = ['/'] # Result Stack
for i in direc:
if i == "" or i == ".": # Base cases
continue
if i=="..": # Return to upper directory
if len(ans) > 1: # No-op case
ans.pop()
ans.pop()
continue
else:
continue
ans.append(i)
ans.append('/')
if len(ans)>2: # Removing '/' from the end
ans.pop()
return "".join(ans) # Generating The String
# Contibuted By - Vaishnav Jha
Thank you
Oshi Raghav