題目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
題意:
給定一個Unix風格的路徑,簡化它。
例子如上。
思路:
處理這類題目就是要處理好不同的細節。比如”/../”這個時候就需要返回”/”,因爲..出來一個路徑,此時已經是根目錄了,所以無法再出。如果是/..a或者/.a或者/…,..a以及.a,…都是有效路徑。
使用一個棧存放掃描到的路徑,如果遇到./或者到了末尾只有.那麼就不操作,如果遇到../或者到了末尾只有’..’,則讓棧頂的目錄出棧。
以上。
代碼如下:
class Solution {
public:
string simplifyPath(string path) {
if (path.empty())return "";
stack<string> paths;
int index = 0;
int size = path.size();
while (index < size) {
switch (path[index]){
case '/':index++; break;
case '.':{
if (index < size - 1 && path[index + 1] == '.') {
if (index == size - 2 || (index < size - 2 && path[index + 2] == '/')) {
index += 2;
if (!paths.empty())paths.pop();
}
else {
string tmp;
while (index < size && path[index] != '/') {
tmp.push_back(path[index]);
index++;
}
paths.push(tmp);
}
}
else if (index == size - 1 || (index < size - 1 && path[index + 1] == '/')) {
index++;
}
else {
string tmp;
while (index < size && path[index] != '/') {
tmp.push_back(path[index]);
index++;
}
paths.push(tmp);
}
break;
}
default:{
string tmp;
while (index < size && path[index] != '/') {
tmp.push_back(path[index]);
index++;
}
paths.push(tmp);
break;
}
}
}
string result = "";
string temp;
while (!paths.empty()) {
result = "/" + paths.top() + result;
paths.pop();
}
return (result == "") ? "/" : result;
}
};