Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
简化路径,linux下面简单的路径操作而已,代码如下:
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 stack<string> tokenStk; 5 int sz = path.size(); 6 for (int i = 0; i < sz; ++i){ 7 if (path[i] == ‘/‘) continue; 8 else{ 9 string tmp = ""; 10 for (int j = i; j < sz && path[j] != ‘/‘; ++j, ++i){ 11 tmp.append(1, path[i]); 12 } 13 if (tmp == ".."){ 14 if (!tokenStk.empty())tokenStk.pop(); 15 } 16 else if (tmp == ".") 17 continue; 18 else 19 tokenStk.push(tmp); 20 } 21 } 22 23 vector<string> tokenVec; 24 while (!tokenStk.empty()){//存储的是反向的目录,将其输出打vector中,这样比较好 25 tokenVec.push_back(tokenStk.top()); 26 tokenStk.pop(); 27 } 28 string ret; 29 if (tokenVec.empty()) ret.append(1, ‘/‘); 30 for (int i = tokenVec.size() - 1; i >= 0; --i){ 31 ret.append(1, ‘/‘); 32 ret.append(tokenVec[i]); 33 } 34 return ret; 35 } 36 };
PS:应为短的if不喜欢加上{}的原因,找bug找了好久,下次不能继续这个坏习惯,mark一下。
时间: 2024-10-17 12:10:52