代码实现:
// 分割'/'得到名字 char **split(const char *s, int *returnSize) { int n = strlen(s); char **ans = (char **)malloc(sizeof(char *) * n); int l = 0, r = 0, len = 0; while (r < n) { while (r < n && s[r] == '/') { r++; } l = r; while (r < n && s[r] != '/') { r++; } if (l < n) { ans[len] = (char*)malloc(sizeof(char) * (r - l + 1)); strncpy(ans[len], s + l, r - l); ans[len][r - l] = '\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 top = -1; for (int i = 0; i < namesSize; ++i) { if (!strcmp(names[i], "..")) { // 遇到".." if (top > -1) { top--; } } else if (!strcmp(names[i], ".")) { // 遇到"." 跳过 continue; } else { if (top == -1 || strcmp(stack[top], names[i])) { // 遇到目录名 stack[++top] = names[i]; } } } char *ans = (char*)malloc(sizeof(char) * (n + 1)); int ind = 0; if (top == -1) { ans[ind] = '/'; ind++; } else { for (int i = 0; i <= top; i++) { ans[ind++] = '/'; strcpy(ans + ind, stack[i]); ind += strlen(stack[i]); } } ans[ind] = '\0'; for (int i = 0; i < namesSize; i++) { free(names[i]); } free(names); free(stack); return ans; }