[LeetCode] 101: Simplify Path

来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/06/05 00:08
[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:
string simplifyPath(string path) {
// Note: The Solution object is instantiated only once and is reused by each test case.
stack<string> myStack;
int i = 0, j = 0;

// move i to the position of the first path
while(i < path.size() && path[i] == '/')i++;

// add all path into the stack
while(i < path.size()){
j = i;
while(j < path.size() && path[j] != '/'){
j++;
}

// sub path
string sub = path.substr(i, j-i);
if(sub == ".."){
if(!myStack.empty()){
myStack.pop();
}
}
else if(sub.size() > 0 && sub != "."){
myStack.push(sub);
}
i = j+1;
}

// generate result
string res = "";
while(!myStack.empty()){
res = "/" + myStack.top() + res;
myStack.pop();
}
if(res == "")res = "/";

return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客