题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
"/../"?"/".‘/‘ together,
such as "/home//foo/"."/home/foo".思路:这是Linux内核中较常见的一个操作,就是对一个输入的文件路径进行简化。我们先来了解一下这些符号在Unix路径中代表的意义:
int compare (const string& str) const;如果相等,返回0;
if(tmp.compare(".") == 0)if(ret.size() == 0)
return "/";4. 注意如何获取分隔符“/”之间的元素,并进行操作,我们遍历一遍path. while(i < path.size())
{
int index = i;
//截取‘/’之间的字符串
string tmp;
while(i < path.size() && path[i] != '/')
{
tmp += path[i];
i++;
}5. 先获取队列头的元素,再pop_front(), 转换成正常路径。while(!stk.empty())
{
ret += "/" + stk.front();
stk.pop_front();
}class Solution {
public:
string simplifyPath(string path) {
if(path.size() == 0) return "";
list<string> stk;
string ret;
int i = 0;
while(i < path.size())
{
int index = i;
//截取‘/’之间的字符串
string tmp;
while(i < path.size() && path[i] != '/')
{
tmp += path[i];
i++;
}
if(index != i)
{
if(tmp.compare(".") == 0)
{
continue;
}
else if(tmp.compare("..") == 0)
{
if(!stk.empty())
{
stk.pop_back();
}
}
else
{
stk.push_back(tmp);
}
}
i++;
}
while(!stk.empty())
{
ret += "/" + stk.front();
stk.pop_front();
}
if(ret.size() == 0)
return "/";
return ret;
}
};[C++]LeetCode: 117 Simplify Path (简化Unix路径 list双向链表)
原文:http://blog.csdn.net/cinderella_niu/article/details/43052745