您的位置:首页 > 其它

[LintCode] Simplify Path 简化路径

2016-07-28 23:54 417 查看
Given an absolute path for a file (Unix-style), simplify it.

Have you met this question in a real interview?

Example

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


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


Challenge

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

LeetCode上的原题,请参见我之前的博客Simplify Path

解法一:

class Solution {
public:
/**
* @param path the original path
* @return the simplified path
*/
string simplifyPath(string& path) {
int left = 0, right = 0, n = path.size();
stack<string> s;
string res = "";
while (right < n) {
while (left < n && path[left] == '/') ++left;
right = left;
while (right < n && path[right] != '/') ++right;
string t = path.substr(left, right - left);
if (t == "..") {
if (!s.empty()) s.pop();
} else if (t != ".") {
if (!t.empty()) s.push(t);
}
left = right;
}
while (!s.empty()) {
res = "/" + s.top() + res; s.pop();
}
return res.empty() ? "/" : res;
}
};


解法二:

class Solution {
public:
/**
* @param path the original path
* @return the simplified path
*/
string simplifyPath(string& path) {
string res, t;
stringstream ss(path);
vector<string> v;
while (getline(ss, t, '/')) {
if (t == "" || t == ".") continue;
if (t == ".." && !v.empty()) v.pop_back();
else if (t != "..") v.push_back(t);
}
for (string s : v) res += "/" + s;
return res.empty() ? "/" : res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: