题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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"
.
1. 将输入字符串以'/'为分隔符分割成子串保存在字符串数组中
2. 遍历1生成的字符串数组,每当碰到非"."和".."的字符串,就将该字符串前加"/",并压入到一个字符串堆栈中(用vector实现,方便最后拼接路径)
每当碰到"."时,直接continue
每当碰到".."时,堆栈弹出一个元素
3. 遍历完成后,将堆栈中剩余的字符串按先进先出的顺序(用vector可以两端访问元素)拼接成最后的路径
若堆栈为空,则返回"/"。
class Solution {
public:
string simplifyPath(string path) {
if(!path.length())
return path;
vector<string> split;
for(int i = 0; i < path.length();)
{
if(path[i] == '/')
{
i++;
continue;
}
else {
string temp = "";
while(path[i] != '/' && i < path.length())
{
temp.insert(temp.length(), 1, path[i++]);
}
split.push_back(temp);
}
}
vector<string> combine;
for(int i = 0; i < split.size(); i++)
{
if(split[i] != "." && split[i] != "..")
{
string path1 = "";
path1.insert(path1.length(), 1, '/');
path1.insert(path1.length(), split[i]);
combine.push_back(path1);
}
else if(split[i] == ".." && combine.size())
{
combine.pop_back();
}
else{
continue;
}
}
string final = "";
if(!combine.size())
{
final.insert(final.length(), 1, '/');
}
for(int i = 0; i < combine.size(); i++)
{
final.insert(final.length(), combine[i]);
}
return final;
}
};