Sunday, February 21, 2016

LeetCode Q71: Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"


class Solution {
public:
string simplifyPath(string path) {
string res="";
stack<string> myStack;
if(path.empty())
return res;
string str="";
path=path+"/";
for(int i=0; i<path.length(); ++i){
char c=path[i];
if(c=='/'){
if(str.empty()||str==string(".")) {
str="";
continue;
}
if(str==string("..")){
if(!myStack.empty())
myStack.pop();
str="";
continue;
}
myStack.push(str);
str="";
continue;
}
else{
str=str+path[i];
}
}
while(!myStack.empty()){
res="/"+myStack.top()+res;
myStack.pop();
}
res=res.empty()? "/":res;
return res;
}
};

No comments:

Post a Comment