problem:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
需注意以下几种情况:
1.重复连续出现的'/',只按1个处理,即跳过重复连续出现的'/';
2.如果路径名是".",则不处理;
3.如路径名是"..",则需要弹栈,如果栈为空,则不做处理;
4.如果路径名为其他字符串,入栈。
class Solution {
public:
string simplifyPath(string path) {
stack<string> temp;
for(int i=0; i<path.size(); )
{
//ignore /
while(i<path.size() && '/' == path[i])
i++;
//record path name
string ss;
while(i<path.size() && path[i] != '/')
ss += path[i++];
//if .., pop
if(".."==ss && !temp.empty())
temp.pop();
else if(ss!="" && ss!="." && ss!="..")
temp.push(ss);
}
//if empty, return /
if(temp.empty())
return "/";
string result;
while(!temp.empty())
{
result = "/" + temp.top() + result;
temp.pop();
}
return result;
}
};