示例 1:
输入:path = “/home/”
输出:“/home”
解释:注意,最后一个目录名后面没有斜杠。
示例 2:
输入:path = “/…/”
输出:“/”
解释:从根目录向上一级是不可行的,因为根目录是你可以到达的最高级。
示例 3:
输入:path = “/home//foo/”
输出:“/home/foo”
解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。
示例 4:
输入:path = “/a/./b/…/…/c/”
输出:“/c”
提示:
1 <= path.length <= 3000
path 由英文字母,数字,‘.’,‘/’ 或 ‘_’ 组成。
path 是一个有效的 Unix 风格绝对路径。
### 题解
[外链图片转存中…(img-5c4J9Ixm-1641480644397)]
**C**
char ** split(const char * s, char delim, int * returnSize) {
int n = strlen(s);
char ** ans = (char **)malloc(sizeof(char *) * n);
int pos = 0;
int curr = 0;
int len = 0;
while (pos < n) {
while (pos < n && s[pos] == delim) {
++pos;
}
curr = pos;
while (pos < n && s[pos] != delim) {
++pos;
}
if (curr < n) {
ans[len] = (char \*)malloc(sizeof(char) \* (pos - curr + 1));
strncpy(ans[len], s + curr, pos - curr);
ans[len][pos - curr] = '\0';
++len;
}
}
\*returnSize = len;
return ans;
}
char * simplifyPath(char * path){
int namesSize = 0;
int n = strlen(path);
char ** names = split(path, ‘/’, &namesSize);
char ** stack = (char **)malloc(sizeof(char *) * namesSize);
int stackSize = 0;
for (int i = 0; i < namesSize; ++i) {
if (!strcmp(names[i], “…”)) {
if (stackSize > 0) {
–stackSize;
}
} else if (strcmp(names[i], “.”)){
stack[stackSize] = names[i];
++stackSize;
}
}
char \* ans = (char \*)malloc(sizeof(char) \* (n + 1));
int curr = 0;
if (stackSize == 0) {
ans[curr] = '/';
++curr;
} else {
for (int i = 0; i < stackSize; ++i) {
ans[curr] = '/';
++curr;
strcpy(ans + curr, stack[i]);
curr += strlen(stack[i]);
}
}
ans[curr] = '\0';
for (int i = 0; i < namesSize; ++i) {
free(names[i]);
}
free(names);
free(stack);
return ans;
}
**C++**
class Solution {
public:
string simplifyPath(string path) {
auto split = [](const string& s, char delim) -> vector {
vector ans;
string cur;
for (char ch: s) {
if (ch == delim) {
ans.push_back(move(cur));
cur.clear();
}
else {
cur += ch;
}
}
ans.push_back(move(cur));
return ans;
};
vector<string> names = split(path, '/');
vector<string> stack;
for (string& name: names) {
if (name == "..") {
if (!stack.empty()) {
stack.pop\_back();
}
}
else if (!name.empty() && name != ".") {
stack.push\_back(move(name));
}
}
string ans;
if (stack.empty()) {
ans = "/";
}
else {
for (string& name: stack) {
ans += "/" + move(name);
}
}
return ans;
}
};
**C++**
class Solution {
public:
string simplifyPath(string path) {
deque st;
int n = path.size(), i = 0;
while(i < n){
if(i < n && path[i] == ‘/’) i++;
else{
string temp;
while(i < n && path[i] != ‘/’) temp += path[i++];
if(temp == “…” && !st.empty()) st.pop_back();
else if(temp != “…” && temp != “.”) st.push_back(temp);
}
}
string res = “/”;
while(!st.empty()){