您的位置:首页 > 其它

[Leetcode 60] 71 Simplify Path

2013-05-26 12:33 501 查看
Problem:

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

Analysis:

Simulation problem, with the help of a vector keeping record of the current path and either push a new path node or pop the older path node or do nothing to maintain the final path.

Need to pay special attention to those corner cases.

Code:

class Solution {
public:
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> stack;
stack.push_back("/");

int p1 = 0, p2 = 0;
while (true) {
while (path[p1] == '/' && p1<path.size())
p1++;

p2 = p1+1;
while (path[p2] != '/' && p2<path.size())
p2++;

if (p2 > path.size()) break;

string tmp = path.substr(p1, p2-p1);
if (tmp == "..") {
if (stack.size() != 1)
stack.pop_back();
}
else if (tmp == ".")
;//do nothing
else
stack.push_back(tmp);

p1 = p2;
}

if (stack.size() == 1)
return "/";
else {
string tmp;
for (int i=1; i<stack.size(); i++)
tmp += "/" + stack[i];
return tmp;
}
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: