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; } };