Simplify Path Problem: 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.
Example :
Input: path = "/home/" Output: "/home" Explanation: Note that there is no trailing slash after the last directory name.
Table of Contents
Simplify Path Problem Solution
Problem Solution In Python
class Solution:
def simplifyPath(self, path: str) -> str:
path = path.split('/')
print(path)
stack = []
for c in path:
if c:
if c == '.':
continue
elif c == '..':
if stack:
stack.pop()
else:
continue
else:
stack.append(c)
return '/'+'/'.join(stack)
Problem Solution In Java
class Solution {
public String simplifyPath(String path) {
String[] arr=path.split("/");
Stack<String> s=new Stack();
for(String str: arr){
if(str.equals(".") || str.length()==0){
continue;
}else if(str.equals("..")){
if(s.size()>0){
s.pop();
}
}else{
s.push(str);
}
}
String ans="";
while(s.size()>0){
ans="/"+s.pop()+ans;
}
if(ans.length()==0){
ans="/";
}
return ans;
}
}
Problem Solution In C++
class Solution {
public:
string simplifyPath(string path) {
vector<string> lks;
for (int i = 0; i < path.length();) {
if (path[i] != '/') {
string dir = "";
while (i < path.length() && path[i] != '/') dir+=path[i++];
if(dir == ".."){
if(lks.size())
lks.pop_back();
}
else if (dir != ".") {
lks.push_back(dir);
}
}
else ++i;
}
string ans="";
for(string x : lks) ans += "/"+ x;
return !ans.length() ? "/" :ans;
}
};
Problem Solution In C
char * simplifyPath(char * path){
char *dirs[100], *p = path, dir_top = -1;
while (*path) {
char *slash1 = strchr(path, '/');
char *slash2 = strchr(slash1 + 1, '/');
slash2 ? *slash2 = 0 : 0;
if (isalpha(slash1[1]))
slash1[1] ? dirs[++dir_top] = strdup(slash1 + 1) : 0;
else if (slash1[1] == '.' && slash1[2] == '.')
slash1[3] == '/' || !slash1[3] ? dir_top >= 0 ? dir_top-- : 0 :
(dirs[++dir_top] = strdup(slash1 + 1), 0);
else if (slash1[1] == '.' && slash1[2] && slash1[2] != '/')
slash1[1] ? dirs[++dir_top] = strdup(slash1 + 1) : 0;
slash2 ? *slash2 = '/' : 0;
path = slash2 ? slash2 : "";
}
for (int i = (strcpy(p, "/"), 0) ; i <= dir_top && (strcat(p, dirs[i]), free(dirs[i]), 1) ; ++i <= dir_top ? strcat(p, "/") : 0);
return p;
}