In the 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.
Example 1:
Input: path = “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
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.
Example 3:
Input: path = “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Constraints:
- 1 <= path.length <= 3000
- path consists of English letters, digits, period ‘.’, slash ‘/’ or ‘_’.
- path is a valid absolute Unix path.
Solution in C Programming
char * simplifyPath(char * path){
bool ignore_slashes;
unsigned short path_length;
unsigned short reader_head, writer_head;
ignore_slashes = false;
path_length = strlen(path);
reader_head = 0, writer_head = 0;
while (reader_head < path_length) {
if (path[reader_head] == '/') {
if (ignore_slashes) {
reader_head++;
continue;
} else {
ignore_slashes = true;
path[writer_head] = '/';
writer_head++;
reader_head++;
continue;
}
} else if ((path[reader_head] == '.') && ignore_slashes) {
if ((reader_head+1 < path_length)
&& (path[reader_head]=='.') && (path[reader_head+1]=='.')
&& ((reader_head+2 == path_length) || (path[reader_head+2]=='/'))) {
/* Go back - we have /..<END> or /../ */
if (writer_head == 1) {
/* noop */
} else {
writer_head -= 2;
while ((writer_head > 0) && path[writer_head] != '/') writer_head--;
writer_head++;
}
reader_head = reader_head+3;
continue;
} else if ((path[reader_head]=='.')
&& ((reader_head+1 == path_length) || (path[reader_head+1]=='/'))) {
/* Ignore- we have /.<END> or /./ */
reader_head = reader_head+2;
continue;
} else {
/* this is a dot but it has something else after it */
ignore_slashes = false;
path[writer_head] = path[reader_head];
reader_head += 1;
writer_head += 1;
continue;
}
} else {
ignore_slashes = false;
path[writer_head] = path[reader_head];
reader_head += 1;
writer_head += 1;
continue;
}
}
if ((writer_head > 1) && (path[writer_head-1] == '/')) {
writer_head--;
}
path[writer_head] = 0;
return path;
}
Solution in C++ Programming
class Solution {
public:
string simplifyPath(string path) {
string ans="";
int n=path.size();
vector<string> v;
int low=0,high=1;
for(int i=1;i<n;i++){
if(path[i]=='/' && path[i-1]!='/'){
string x= path.substr(low+1,i-low-1);
if(x=="."){
low=i;
continue;
}
if(x==".."){
if(v.size()==0){
low=i;
continue;
}
v.pop_back();
}
else
v.push_back(x);
low=i;
}
if(path[i]=='/' && path[i-1]=='/')
low=i;
}
// cout<<low<<endl;
// for(auto &it : v)
// cout<<it<<endl;
// cout<<path.substr(low+1,n-1-(low))<<endl;
if(low<n-1){
if(path.substr(low+1,n-1-(low))==".."){
if(v.size())v.pop_back();
}
if(path.substr(low+1,n-1-(low))!="." && path.substr(low+1,n-1-(low))!="..")
v.push_back(path.substr(low+1,n-1-(low)));
}
for(int i=0;i<v.size();i++){
ans+='/';
ans+=v[i];
}
if(v.size()==0)ans.push_back('/');
return ans;
}
};
Solution in Java Programming
class Solution {
public static String simplifyPath(String path) {
if (path == null || path.length() == 0)
return null;
String[] parts = path.split("/");
Stack<String> stack = new Stack<>();
for (int i = 0; i < parts.length; i++) {
if (parts[i].equals(".")||parts[i].equals(""))
continue;
else if (parts[i].equals("..")) {
if (!stack.isEmpty())
stack.pop();
else
continue;
} else
stack.push(parts[i]);
}
if (stack.isEmpty())
return "/";
String result = "";
while (!stack.isEmpty()) {
result = "/" + stack.pop() + result;
}
return result;
}
}
Solution in Python Programming
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack = []
for directory in path.split("/"):
if not directory or directory == ".":
continue
elif directory == "..":
if stack:
stack.pop()
else:
stack.append(directory)
return "/" + "/".join(stack)
Solution in C# Programming
public class Solution {
public string SimplifyPath(string path) {
if(String.IsNullOrEmpty(path))
return "";
Stack<string> st=new Stack<string>();
string[] pathArr=path.Split("/");
for(int i=0;i<pathArr.Length;i++)
{
if(String.IsNullOrEmpty(pathArr[i]) || pathArr[i]==".")
continue;
else if(pathArr[i]=="..")
{
if(st.Count>0)
st.Pop();
}
else
st.Push("/"+pathArr[i]);
}
string retVal="";
while(st.Count!=0)
retVal=st.Pop()+retVal;
return String.IsNullOrEmpty(retVal)?"/":retVal;
}
}
Also read,