Simplify Path
LeetCode #71
Description:
Given an absolute path for a file (Unix-style), simplify it.
Example:
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
if "/..."
output: "/..."
Idea:
用stack,不过用vector来模拟。 中间用到find来找下一个'\'position.
Code:
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack_s; // Use as stack,
// if use real stack, print out result will be difficult
for(auto i=path.begin(); i!=path.end();){
if(*i=='/'){
i++;
continue;
}
auto j=find(i, path.end(), '/');
string sub_s(i, j);
cout<<sub_s<<endl;
if(sub_s!="."){
if(sub_s==".."){
if(!stack_s.empty()){
stack_s.pop_back();
}
}
else{
stack_s.push_back(sub_s);
}
}
i=j;
}
if(stack_s.empty()) return "/";
string result;
for(auto e: stack_s){
result += "/" + e;
}
return result;
}
};