Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
class Solution { public: string simplifyPath(string path) { string ret; stack<string> stackPath; int len = path.length(); int start = 1; if(len <= 1) return path; for (int i = 1; i < len; i++) { if(path[i] == '/'){ string str = path.substr(start,i-start); start = i+1; if(str == ".."){ if(!stackPath.empty()) stackPath.pop(); }else if(str == "."){ continue; }else if(str.length() > 0){ stackPath.push(str); } } } if (start < len) { string str = path.substr(start, len - start); if (str == "..") { if (!stackPath.empty()) stackPath.pop(); } else if (str != ".") { ret = "/" + str; } } while(!stackPath.empty()){ ret = "/" + stackPath.top() + ret; stackPath.pop(); } if(ret.length()==0) ret = "/"; return ret; } };