LeetCode·71. Simplify Path
程序员文章站
2022-03-05 11:37:47
...
题目:
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".
思路:
- 解决尾部;
- 解决
"//"
情况; - 分割路径处理;
代码:
class Solution {
public:
string simplifyPath(string path) {
if(path.size() <= 1)
return path;
if(path[path.size()-1] == '/'){
for(int i = path.size()-1; i > 1; --i){
if(path[i] == '/')
path = path.substr(0, i);
else
break;
}
}
for(int i = 0; i < path.size()-1; ++i){
if(path[i] == '/' && path[i+1] == '/'){
path = path.substr(0, i) + path.substr(i+1, path.size());
}
}
vector<string> vec;
string str = "";
for(int i = 0; i < path.size(); ++i){
if(path[i] != '/'){
str += path[i];
}else{
if(str != ""){
vec.push_back(str);
str = "";
}
}
}vec.push_back(str);
for(int i = 0; i < vec.size(); ++i){
if(vec[i] == "."){
vector<string>::iterator it = vec.begin()+i;
vec.erase(it);
--i;
}else if(vec[i] == ".."){
vector<string>::iterator it = vec.begin()+i;
vec.erase(it);
if(i == 0){
--i;
continue;
}
it = vec.begin()+i-1;
vec.erase(it);
--i;--i;
}
}
str = "/";
for(int i = 0; i < vec.size(); ++i){
str += vec[i];
if(i != vec.size()-1)
str += "/";
}
return str;
}
};
结果:
推荐阅读
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化
-
[LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
-
LeetCode刷题之71.简化路径
-
LeetCode学习笔记(6) 第124题 Binary Tree Maximum Path Sum
-
LeetCode112.Path Sum
-
C++实现LeetCode(71.简化路径)
-
leetcode 71. Simplify Path(Unix下简化路径)
-
leetcode 1368. Minimum Cost to Make at Least One Valid Path in a Grid
-
LeetCode112.Path Sum
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化