Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
字符串最麻烦~折腾
class Solution {
public:
void getnext(const string& str, int& start, int& end) {
while (start < str.size() && str[start] == '/') start++;
if (start == str.size()) {start =-1; return;}
end = start;
while (end < str.size() && str[end] != '/') end++;
}
string simplifyPath(string path) {
char* a = new char[path.size()];
memset(a, 0, path.size());
int pos = 0, end = 0;
while (end < path.size()) {
getnext(path, pos, end);
if (pos == -1) break;
int l = end - pos;
string sub = path.substr(pos, l);
if (sub.compare(".") == 0) {
} else if (sub.compare("..") == 0) {
int last = strlen(a) - 1;
while (last >= 0 && a[last] != '/') last--;
if(last < 0) a[0] = '\0';
else a[last] = '\0';
} else {
strcat(a, "/");
strcat(a, sub.c_str());
}
pos = end + 1;
}
if (strlen(a) == 0) {a[0] = '/'; a[1] = '\0';}
string res(a);
delete []a;
return res;
}
};
class Solution {
public:
string simplifyPath(string path) {
int n = path.size();
auto& a = path;
if (n == 0) return path;
char *c = new char[n+1];
memcpy(c, path.c_str(), n+1);
int idx = 0;
char *s = c, *e;
while (*s != '\0') {
s = getFirst(s);
e = getLast(s);
if (*s == '\0') break;
if (e == s && *s == '.') s = e + 1;
else if (e - s == 1 && *s == '.' && *e == '.') {
if (idx > 0)
idx = up(c, idx-1);
s = e+1;
}
else {
c[idx++] = '/';
while (s <= e) c[idx++] = *s++;
}
}
if (idx == 0) c[idx++] = '/';
c[idx] = '\0';
return string(c);
}
int up(char*c, int i) {
while (i > 0 && c[i] != '/') i--;
return i;
}
char* getFirst(char *c) {
while (*c == '/') c++;
return c;
}
char* getLast(char * c) {
while (*c != '/' && *c != '\0') c++;
return c-1;
}
};
路径简化算法详解

本文深入探讨了如何将Unix风格的绝对路径进行简化的过程,通过分析并实现两种不同的算法,旨在帮助开发者更高效地处理文件路径相关的问题。
1586

被折叠的 条评论
为什么被折叠?



