unix简化路径
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
#include <iostream> #include <vector> #include <sstream> using namespace std; class Solution { public: string simplifyPath(string path) { string res; string tmp; vector<string> vec; stringstream ss(path); while(getline(ss,tmp,'/')) { if(tmp == "" or tmp == ".") continue; if(tmp == ".." and !vec.empty()) { vec.pop_back(); } else if(tmp != "..") { vec.push_back(tmp); } } for(string str:vec) { res += "/" + str; } return res.empty()?"/":res; } }; int main() { string str; cin>>str; Solution s; cout<<s.simplifyPath(str)<<endl; return 0; }