Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Simplify_Path.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
public:
string simplifyPath(string path) {

stack<string> st;
string res;

for(int i = 0; i<path.size(); ++i)
{
if(path[i] == '/')
continue;
string temp;
// iterate till we doesn't traverse the whole string and doesn't encounter the last /
while(i < path.size() && path[i] != '/')
{
// add path to temp string
temp += path[i];
++i;
}
if(temp == ".")
continue;
// pop the top element from stack if exists
else if(temp == "..")
{
if(!st.empty())
st.pop();
}
else
// push the directory file name to stack
st.push(temp);
}

// adding all the stack elements to res
while(!st.empty())
{
res = "/" + st.top() + res;
st.pop();
}

// if no directory or file is present
if(res.size() == 0)
return "/";

return res;
}
};