zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Xcode7下模拟器输入文本无法显示系统键盘的解决办法
    Mac系统下开启和关闭隐藏文件的方法
    iOS常用第三方开源框架和优秀开发者博客等
    UILabel 的一个蛋疼问题
    学习进度条
    学习进度条
    四则运算2
    学习进度条
    第一次被要求连接数据库的课堂测试
    课后作业06多态与接口
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099853.html
Copyright © 2011-2022 走看看