您的位置:首页 > 其它

Leetcode 71. Simplify Path

2018-02-04 06:44 274 查看
原题:
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"
.

解决方法:
用deque来保存读到的路径,用stringstream来切分字符串。当读到".."时,deque删除最后一个路径。最后把所有读到的路径拼起来即可。

代码:
string simplifyPath(string path) {
deque<string> d;

string res, temp;
stringstream s(path);
while(getline(s,temp, '/')){
if (temp.empty() || temp ==".")
continue;

if (temp == ".."){
if (!d.empty())
d.pop_back();
}else{
d.push_back(temp);
}
}

for(auto item: d){
res +=  "/" + item;
}

return res.empty() ? "/" : res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C Leetcode