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

    这里用了一个vector来模拟栈。方便正序输出。

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         if (path.empty()) return "/";
     5         path.push_back('/');
     6         int start = -1, end;
     7         vector<string> st;
     8         while ((end = path.find('/', start + 1)) != string::npos) {
     9             string tmp = "";
    10             if (end - start - 1) {
    11                 tmp = path.substr(start + 1, end - start - 1);
    12             }
    13             if (tmp == ".." && !st.empty()) st.pop_back();
    14             if (!tmp.empty() && tmp != "." && tmp != "..") st.push_back(tmp);
    15             start = end;
    16         }
    17         stringstream ans;
    18         for (int i = 0; i < st.size(); i++) {
    19             ans << '/' << st[i];
    20         }
    21         if (!ans.str().empty()) return ans.str();
    22         return "/";
    23     }
    24 };
  • 相关阅读:
    协议与接口相关
    jmeter 使用(1)
    jmeter 压力测试
    shell脚本的规则
    charles的原理及使用
    Linux环境部署和项目构建
    面向对象
    python 基础练习题
    jmeter 使用(2)
    Ext.apply
  • 原文地址:https://www.cnblogs.com/linyx/p/4046066.html
Copyright © 2011-2022 走看看