Notes:
The question is straightforward, see the pseudo-code below:
def res = "";
if s[i] == '/'
continue;
else
def t = the following string;
if t == ".."
if(res.size()) pop out the least element from res.
else if t == "." continue;
else
save '/' and t into res;
return res
See the code below:
class Solution {
public:
string simplifyPath(string path) {
string res = "";
if(path.empty()) return res;
for(int i=0; i<path.size(); ) {
if(path[i] != '/') {
string t = "";
while(i<path.size() && path[i] != '/') {
t.push_back(path[i++]);
}
if(t == "..") {
while(res.size() && res.back() != '/') res.pop_back();
if(res.size() && res.back() == '/') res.pop_back();
}
else if(t != ".") {
res.push_back('/');
res += t;
}
}
else ++i;
}
if(res.empty()) res = "/";
return res;
}
};
No comments:
Post a Comment