您的位置:首页 > 其它

[leetcode] Simplify Path

2015-07-01 17:36 357 查看
From : https://leetcode.com/problems/simplify-path/
Given an absolute path for a file (Unix-style), simplify it.

For example,

path =
"/home/"
, =>
"/home"


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


click to show corner cases.

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"
.

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