Given an absolute path for a file (Unix-style), simplify it.
For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"
"/home/"
"/home"
"/a/./b/../../c/"
"/c"
click to show corner cases.
class Solution { public: string simplifyPath(string path) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = path.length(); int cwpos = -1, cstart = 0, cend = 0; while (true) { while (cstart < len && path[cstart] == ‘/‘) ++cstart; if (cstart >= len) break; cend = cstart + 1; while (cend < len && path[cend] != ‘/‘) ++cend; int clen = cend - cstart; if (clen > 0 && (clen != 1 || path[cstart] != ‘.‘)) { if (clen == 2 && path[cstart] == ‘.‘ && path[cstart + 1] == ‘.‘) { while (cwpos >= 0 && path[cwpos] != ‘/‘) --cwpos; if (cwpos >= 0) --cwpos; } else { path[++cwpos] = ‘/‘; while (cstart < cend) { path[++cwpos] = path[cstart++]; } } } cstart = cend; } if (cwpos < 0) return "/"; path.resize(cwpos + 1); return path; } };
Simplify Path,布布扣,bubuko.com
Simplify Path
原文:http://blog.csdn.net/icomputational/article/details/23390003