[LeetCode] Simplify Path

来源:互联网 发布:音频测试软件 编辑:程序博客网 时间:2024/06/07 14:12
[Problem]

Given an absolute path for a file (Unix-style), simplify it.

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".

[Solution]

class Solution {
public:
// split path by '/'
vector split(string path){
int i = 0;
string str = "";
vector res;
while(i < path.length()){
if(path[i] == '/'){
if(str != ""){
res.push_back(str);
str = "";
}
}
else{
str += path[i];
}
i++;
}

// be careful the last path
if(str != ""){
res.push_back(str);
}
return res;
}

// simplify path
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
deque myQueue;
myQueue.push_back("/");

// split path
vector dirs = split(path);

// enqueue
for(int i = 0; i < dirs.size(); ++i){
if(dirs[i] == "."){
continue;
}
else if(dirs[i] == ".."){
if(myQueue.back() == "/" && myQueue.size() == 1){
continue;
}
else{
// pop dir
myQueue.pop_back();

// pop '/'
if(myQueue.size() > 1){
myQueue.pop_back();
}
}
}
else{
if(myQueue.back() != "/"){
myQueue.push_back("/");
}
myQueue.push_back(dirs[i]);
}
}

// dequeue
string res = "";
while(!myQueue.empty()){
res += myQueue.front();
myQueue.pop_front();
}
return res;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击