class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
size_t loc = path.find_first_of('/');
path = path.substr(loc);
while(!path.empty()) {
loc = path.find_first_not_of('/');
if(loc == string::npos) {
break;
}
path = path.substr(loc);
size_t end = path.find_first_of('/');
string token;
if(end == string::npos) {
token = path;
} else {
token = path.substr(0, end);
}
if(token == ".") {
} else if(token == "..") {
if(!stack.empty()) {
stack.pop_back();
}
} else {
stack.emplace_back(token);
}
if(end == string::npos) {
break;
} else {
path = path.substr(end);
}
}
string result("/");
for(string& str : stack) {
result += str + "/";
}
if(result != "/") {
result = result.substr(0, result.length() - 1);
}
return result;
}
};
4/09/2014
Leetcode -- Simplify Path
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment