标签:
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) { stack<char> pathStack; pathStack.push(path[0]); for(int i =1; i<path.length(); i++) { if(path[i]==‘/‘) { if(pathStack.top() == ‘/‘) continue; //ignore second ‘/‘ else if(pathStack.top()==‘.‘) //ignore ‘./‘ { pathStack.pop(); } else { pathStack.push(path[i]); } } else if(path[i]==‘.‘) { if(pathStack.top() != ‘.‘) { pathStack.push(path[i]); continue; } pathStack.pop(); //pop ‘/..‘中的第一个‘.‘ if(pathStack.size()==1) continue; pathStack.pop(); //pop ‘/..‘中的‘/‘ while(pathStack.top() != ‘/‘) pathStack.pop(); //pop ‘/..‘的上一个文件路径 if(pathStack.size()>1){ pathStack.pop(); } } else { pathStack.push(path[i]); } } while(pathStack.size()>1 && (pathStack.top()==‘/‘ || pathStack.top()==‘.‘)) pathStack.pop(); //path最后的‘.‘和‘/‘要去掉 //stack中剩余的是要return的path if(pathStack.empty()) return "/"; int len = pathStack.size(); path = path.substr(0,len); while(!pathStack.empty()) { path[--len]=pathStack.top(); pathStack.pop(); } return path; } }
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4854127.html