您的位置:首页 > 其它

71.Simplify Path

2016-10-16 11:45 141 查看
题目:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = 
"/home/"
, => 
"/home"

path 
"/a/./b/../../c/"
, => 
"/c"


思路:

1、边界情况:如果只输入'/':直接返回"/"即可

2、做这道题需要了解linux系统下的绝对路径与相对路径的关系:

(1)相对路径中的 '.' 表示该路径,不进行上下层路径的转换,可以忽略

(2)相对路径中的 '..' 表示当前路径的上一层,比如/ab/cd/.. ,即返回/ab

3、首先想到用栈,然后考虑,是在读取path时处理相对路径,还是从栈中取值时处理。

因为用后者的话,比如遇到/../..这种情况,无法处理。所以选第一种方案。

4、具体处理方案:遇到'/', 入栈;遇到"."或者""时,跳过;遇到"..",跳过并进行出栈

代码:

string simplifyPath(string path) {
if (path == "/")    return "/";
if (path[path.size() - 1] != '/')
path += '/';
stack<string> s;
string temp,dst;
for (int i = 0; i< path.size(); i++){
if (path[i] != '/')
temp += path[i];
else{
if (temp == "." || temp == ""){}
else if (temp == ".."){
if (!s.empty()) s.pop();
}else    s.push(temp);
temp = "";
}
}
while (!s.empty()){
dst = "/" + s.top() + dst;
s.pop();
}
if (dst == "")  return "/";
else    return dst;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Simplify Path