参考:http://blog.youkuaiyun.com/makuiyu/article/details/44497901
题意
将linux下的路径名转换成一个与路径等价但最短的路径名
题解
使用栈来记录普通路径名(遇到“.”则跳过;“..”则出栈一个普通路径名)
代码
class Solution {
public:
string simplifyPath(string path) {
int len = path.length();
stack<string> dirs;
for(int i = 0; i < len;)
{
string temp;
while(i < len && path[i] == '/')
i++;
while(i < len && path[i] != '/')
temp += path[i++];
if(temp == "..")
{
if(!dirs.empty())
dirs.pop();
}
else if(temp != "." && temp != "")
dirs.push(temp);
}
string result = "";
while(!dirs.empty())
{
result = "/" + dirs.top() + result;
dirs.pop();
}
if(result == "")
return "/";
return result;
}
};