Description:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
分析:此题是将Unix-style的路径简化,即将相对路径转化为绝对路径。这道题看着简单,过程十分艰辛。传统的一个个字符读取处理情况太过复杂,写出来的代码凌乱不堪。接下来说一下正确思路,建立一个string的数组res,以“/”为分隔符将path中路径分割存储。如果遇到".",不存储;遇到“..”,若res为空,则不做处理,若不为空,则删除res的最后一个元素。(res的作用类似于栈)。
下面贴的是按照discuss上一个小哥思路的代码:(getline()的用法参照我的博文http://blog.csdn.net/anonymouscrawler/article/details/78900744)
class Solution {
public:
string simplifyPath(string path) {
string res, tmp;
vector<string> spilt;
stringstream ss(path);
while(getline(ss, tmp, "/")
{
if(tmp == "." || tmp == "") //为什么需要判断tmp=="",参考上面链接.
continue;
if(tmp == ".." && !spilt.empty())
spilt.pop_back();
else if(tmp != "..")
spilt.push_back(tmp);
}
for(auto str : spilt)
res = res + "/" + str;
if(res.empty())
return "/";
else
return res;
}
};