代码实现:
栈
// 分割'/'得到名字 char **split(const char *s, int *returnSize) { int n = strlen(s); char **ans = (char**)malloc(sizeof(char*) * n); int l = 0, r; *returnSize = 0; while (l < n) { while (l < n && s[l] == '/') { // 左:l l++; } r = l; while (r < n && s[r] != '/') { // 右:r - 1 r++; } if (l < n) { ans[*returnSize] = (char*)malloc(sizeof(char) * (r - l + 1)); strncpy(ans[*returnSize], s + l, r - l); ans[*returnSize][r - l] = '\0'; (*returnSize)++; } l = r; } 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; }