标签:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
"/../"
?"/"
.‘/‘
together, such as "/home//foo/"
."/home/foo"
.
class Solution { public: string simplifyPath(string path) { vector<string> v; int i = 0; while (i < path.size()) { while (path[i] == ‘/‘ && i < path.size()) ++i; if (i == path.size()) break; int start = i; while (path[i] != ‘/‘ && i < path.size()) ++i; int end = i - 1; string s = path.substr(start, end - start + 1); if (s == "..") { if (!v.empty()) v.pop_back(); } else if (s != ".") { v.push_back(s); } } if (v.empty()) return "/"; string res; for (int i = 0; i < v.size(); ++i) { res += ‘/‘ + v[i]; } return res; } };
标签:
原文地址:http://www.cnblogs.com/grandyang/p/4347125.html