Simplify Path

描述

Given an absolute path for a file (Unix-style), simplify it.

For example,

  • path = "/home/", => "/home"
  • path = "/a/./b/../../c/", => "/c"
    Corner Cases:

  • Did you consider the case where path = "/../"?

    In this case, you should return "/".

  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".

    In this case, you should ignore redundant slashes and return "/home/foo".

分析

很有实际价值的题目。

代码

  1. // Simplify Path
  2. // 时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. string simplifyPath(const string& path) {
  6. vector<string> dirs; // 当做栈
  7. for (auto i = path.begin(); i != path.end();) {
  8. ++i;
  9. auto j = find(i, path.end(), '/');
  10. auto dir = string(i, j);
  11. if (!dir.empty() && dir != ".") {// 当有连续 '///'时,dir 为空
  12. if (dir == "..") {
  13. if (!dirs.empty())
  14. dirs.pop_back();
  15. } else
  16. dirs.push_back(dir);
  17. }
  18. i = j;
  19. }
  20. stringstream out;
  21. if (dirs.empty()) {
  22. out << "/";
  23. } else {
  24. for (auto dir : dirs)
  25. out << '/' << dir;
  26. }
  27. return out.str();
  28. }
  29. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/string/simplify-path.html