zoukankan      html  css  js  c++  java
  • 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".

    Solution: Add an additional '/' at the end of 'path' for simply detecting the end.

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         string res;
     5         path += "/";
     6         size_t pos = path.find_first_of("/"), last = 0;
     7         while(pos != string::npos) {
     8             string s = path.substr(last, pos - last);
     9             if(s == "..") {
    10                 if (!res.empty())
    11                     res.resize(res.find_last_of("/"));
    12             }
    13             else if (!s.empty() && s != ".")
    14             {
    15                 res += "/";
    16                 res += s;
    17             }
    18             last = pos + 1;
    19             pos = path.find_first_of("/", last);
    20         }
    21         return res.empty() ? "/" : res;
    22     }
    23 };
  • 相关阅读:
    并发与并行
    OpenCV 图像集合操作
    C++ 输出时间
    绘制模型图
    检测图像文件是否损坏
    QImage,Mat ,QByteArray转换
    图像拼接3
    图像拼接2】
    图像拼接 Stitcher
    《将博客搬至CSDN》
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3679643.html
Copyright © 2011-2022 走看看