您的位置:首页 > 其它

leetcode---Simplify Path---栈

2016-05-27 22:40 344 查看
Given an absolute path for a file (Unix-style), simplify it.

For example,

path = “/home/”, => “/home”

path = “/a/./b/../../c/”, => “/c”

class Solution {
public:
string simplifyPath(string path)
{
stack<string> s;
string ans = "";
int i = 0;
while(i < path.length())
{
while(i<path.length() && path[i] == '/')
i++;
string name = "";
while(i<path.length() && path[i] != '/')
name += path[i++];
if(name == ".." && !s.empty())
s.pop();
else if(name != "" && name != "." && name != "..")
s.push(name);
}
if(s.empty())
ans = "/";
else
{
while(!s.empty())
{
ans =  "/" + s.top() + ans;
s.pop();
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: