标签:leetcode algorithm stack string simplify path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/"
, =>"/home"
path ="/a/./b/../../c/"
, =>"/c"
这个题目比较简单,用很常规的方法解决即可,测试的时候遇到什么问题再解决就行了。我的C++代码如下:
string simplifyPath(string path) {
string dir;
stack<string> dirs;
for (auto ch : path) {
if (ch != ‘/‘) dir += ch;
else if (!dir.empty()) {
dirs.push(dir);
dir.clear();
}
}
if (!dir.empty()) {
dirs.push(dir);
dir.clear();
}
int popCount = 0;
while (!dirs.empty()) {
auto topDir = dirs.top();
dirs.pop();
if (!topDir.compare(".")) continue;
else if (!topDir.compare("..")) ++popCount;
else if (popCount) --popCount;
else dir.insert(0, "/" + topDir);
}
return dir.empty() ? "/" : dir;
}
时间性能如下图所示:
LeetCode[Stack]: Simplify Path
标签:leetcode algorithm stack string simplify path
原文地址:http://blog.csdn.net/chfe007/article/details/43453447