您的位置:首页 > 其它

Simplify Path

2015-08-10 01:42 363 查看

原题

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息