• [Leetcode 60] 71 Simplify Path


    Problem:

    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".

    Analysis:

    Simulation problem, with the help of a vector keeping record of the current path and either push a new path node or pop the older path node or do nothing to maintain the final path.

    Need to pay special attention to those corner cases.

    Code:

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<string> stack;
     7         stack.push_back("/");
     8         
     9         int p1 = 0, p2 = 0;
    10         while (true) {
    11             while (path[p1] == '/' && p1<path.size())
    12                 p1++;
    13                 
    14             p2 = p1+1;
    15             while (path[p2] != '/' && p2<path.size()) 
    16                 p2++;  
    17             
    18             if (p2 > path.size()) break;
    19             
    20             string tmp = path.substr(p1, p2-p1);        
    21             if (tmp == "..") {
    22                 if (stack.size() != 1)
    23                      stack.pop_back();
    24             }
    25             else if (tmp == ".")
    26                 ;//do nothing
    27             else
    28                 stack.push_back(tmp);
    29             
    30             p1 = p2;
    31         }
    32         
    33         
    34         if (stack.size() == 1)
    35             return "/";
    36         else {
    37             string tmp;
    38             for (int i=1; i<stack.size(); i++)
    39                 tmp += "/" + stack[i];
    40             return tmp;
    41         }
    42     }
    43 };
    View Code
  • 相关阅读:
    namespace for c++
    [爬虫]Python爬虫基础
    为什么局域网IP是192.168开头?
    [Python基础]Python中remove,del和pop的区别
    权限控制(delphi actionlist)
    Delphi ActionList详解
    充分利用HTML标签元素 – 简单的xtyle前端框架
    好用的侧边栏菜单/面板jQuery插件
    最新的手机/移动设备jQuery插件
    有用的jQuery布局插件推荐
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099853.html
Copyright © 2020-2023  润新知