# Easy to grasp, elegant C++ solution

#1
``````string Solution::simplifyPath(string A) {
stack<string> res;
vector<string> s;
string final = "";
int N = A.size();

for(int i = 1; i<N; i++){
string temp = "";
while(A[i] != '/' && i<N){
temp.push_back(A[i]);
i++;
}
if(temp != ".." && temp != "." && temp.length() > 0) res.push(temp);
else if(temp == ".") continue;
else if(temp == ".."){
if(!res.empty()) res.pop();
}
}
while(!res.empty()){
s.push_back(res.top());
s.push_back("/");
res.pop();
}
if(s.size() == 0) s.push_back("/");
reverse(s.begin(), s.end());
for(auto t: s) final+=t;

return final;
}
``````

It might be a bit longer than other solutions, but it’s easier to grasp all the edge cases that arise on InterviewBit through this soln.

#2

Hey, instead of storing the strings in the stack you can directly store them in an array. This will reduce the size of your code.

string Solution::simplifyPath(string A) {
int n = A.size();
vector ans;
for(int i = 1; i<n; i++){
string temp = “”;
while(i<n && A[i] != ‘/’) {
temp += A[i];
i++;
}
if(temp.size()>0 && temp != “.” && temp != “…”) ans.push_back(temp);
else if(temp == “.”) continue;
else if(temp == “…”) if(ans.size()>0) ans.pop_back();
}
string res = “”;
for(int i = 0; i<ans.size(); i++){
res += “/” + ans[i];
}
if(res.size()==0) return “/”;
return res;
}