LeetCode(45) Simplify Path
阿新 • • 發佈:2019-01-12
題目描述
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
本題要求對給定的Unix路徑進行簡化,關鍵點在於理解Unix路徑的規則以及對一些邊界條件要加以考慮。
Unix路徑規則:
字元 | 含義(英文) | 含義(中文) |
---|---|---|
/ | root directory | 根目錄 |
/ | Directory Separator | 路徑分隔符 |
. | Current Directory | 當前目錄 |
.. | Parent Directory | 上級目錄 |
~ | Home Directory | 家目錄 |
Corner Cases:
path = “/../” => 輸出 “/”.
連續的多個分隔符 ‘/’ , 例如 “/home//foo/” => 忽略重複的分隔符,輸出 “/home/foo”.
解題思路
總體來說本題並不難,只要根據unix path規則,細心考慮可能的邊界條件即可。
class Solution {
public:
string simplifyPath(string path) {
char slash = '/';
vector<string> dirs;
int begin = 0, end = 0;
int len = path.length();
while (end < len)
{
begin = end ;
while (begin < len && path[begin] == slash)
begin++;
end = begin;
while (end < len && path[end] != slash)
end++;
if (begin != end)
{
string tmp(path, begin, end - begin);
if (tmp == ".." && !dirs.empty())
dirs.pop_back();
else if (tmp == ".." && dirs.empty())
continue;
else if (tmp != ".")
dirs.push_back(tmp);
}
}
string simplePath = "";
for (size_t i = 0; i != dirs.size(); ++i)
{
simplePath += slash + dirs[i];
}
if(dirs.empty())
simplePath = slash;
return simplePath;
}
};