原题
https://leetcode.com/problems/simplify-path/。
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
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”.
翻译:简化unix文件路径。
思路
其实没什么好讲的,利用栈的结构,然后分情况讨论就行。
代码
class Solution {
public:
string simplifyPath(string path) {
list<string> theList;
string temp, res;
stringstream ss(path);
while(getline(ss,temp,'/'))
{
if(temp == "" || temp == ".") continue;
if(temp == ".." && !theList.empty()) theList.pop_back();
else if(temp != "..") theList.push_back(temp);
}
for(string theTemp : theList) res += "/" + theTemp;
return res.empty() ? "/" : res;
}
};