Simplify Path
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) {
list<string> path_queue;
string current_path;
// ensure committing the last token
path += '/';
// iterate every character
for(size_t i = 0; i < path.size(); ++i)
{
char ch = path[i];
if (ch == '/') // met splitter
{
if (current_path == "." || current_path == "")
;// do nothing
else if (current_path == "..")
{ // pop last path
if (!path_queue.empty())
path_queue.pop_back();
}
else
path_queue.push_back(current_path);
current_path = "";
}
else
current_path += ch;
}
string ret;
for(auto i : path_queue)
if (i != "")
ret += string("/") + i;
if (ret == "")
ret = "/";
return ret;
}
};