class Solution {
public:
string simplifyPath(string path);
};
string Solution::simplifyPath(string path)
{
//去掉所有多余的"/"
regex regex3("\\/{2,}");
path = regex_replace(path, regex3, "/");
regex regex2("\\/{1}\\.{0,2}");
if (regex_match(path, regex2))
return "/";
regex regex1("\\/{1}[\\.a-z]*");
if (regex_match(path, regex1)) {
return path;
}
path += '/';
//替换单个point
smatch sm;
regex reg_single_point("\\/{1}\\.{1}\\/{1}");
while (regex_search(path, reg_single_point))
{
path = regex_replace(path, reg_single_point, "/");
}
//处理两个point
regex reg_double_point("[\\/]{1}[\\.]{2}[\\/]{1}");
while (regex_search(path, sm, reg_double_point))
{
string str_head = sm.prefix();
string str_tail = sm.suffix();
for (int i = str_head.length() - 1; i >= 0; --i) {
if (str_head[i] == '/')
{
str_head.erase(i);
break;
}
}
path = str_head + "/" + str_tail;
}
if (regex_match(path, regex2))
return "/";
if (regex_match(path, regex1)) {
return path;
}
string ans;
for (int j = 0; j < path.length(); ++j) {
if (path[j] != '/')
ans += path[j];
else
{
if (path[j + 1] != '/'&&j < path.length() - 1)
ans += '/';
}
}
if (ans[0] != '/')
ans = '/' + ans;
return ans;
}
71.简化路径
最新推荐文章于 2022-06-13 18:43:36 发布