In this Leetcode Simplify Path Problem Solution 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.
Problem solution in Python.
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for c in path.split('/'):
match c:
case '..':
if stack:
stack.pop()
case ''|'.':
pass
case _:
stack.append(c)
return '/' + '/'.join(stack)
Problem solution in Java.
package com.leetcode.simplifypath;
import java.util.Stack;
public class SimplifyPath {
public String simplifyPathWithStack(String path) {
Stack<String> stack = new Stack<>();
for (String s : path.split("/")) {
if (s.equals("..")) {
if (!stack.isEmpty()) stack.pop();
} else if (!s.isEmpty() && !s.equals(".")) {
stack.push(s);
}
}
return "/" + String.join("/", stack);
}
}
Problem solution in C++.
class Solution {
public:
string simplifyPath(string path) {
stack<string> s;
string ans, temp;
int n = path.size();
stringstream X(path);
while(getline(X, temp, '/')){
if(temp == "" || temp == ".") continue;
if(temp != ".." ) s.push(temp);
else if(!s.empty()) s.pop();
}
if(s.empty()) return "/";
while(!s.empty()){
ans = '/' + s.top() + ans;
s.pop();
}
return ans;
}
};
Problem solution in C.
char* simplifyPath(char* path) {
int i, t=1;
int len = strlen(path);
path[0] = '/';
for(i=1; i<len; i++) {
if(path[i]=='.' && ((i+1<len && path[i+1]=='/') || path[i+1]=='\0')) {
i = i + 1;
} else if(path[i]=='.' && i+1<len && path[i+1]=='.' && ((i+2<len && path[i+2]=='/') || path[i+2]=='\0')) {
i = i + 2;
t = t - 2 < 0? 0: t-2;
while(path[t]!='/') {
t--;
}
t++;
} else if(path[i]=='/') {
continue;
} else {
do {
path[t++] = path[i++];
} while(i<len && path[i]!='/');
path[t++] = path[i];
}
}
if(t>1) {
path[t-1] = '\0';
} else {
path[t] = '\0';
}
return path;
}
0 Comments