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"

    click to show corner cases.

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

    Analyse: We need to understand the meaning of these symbols:

      "/" is the directory seperator. The content between two seperators have following meaning.

      "/." is the current directory, when it's encountered, we just ignore it.

      "/.." is the parent directory, if it's encountered and the stack is not empty, we pop the top element. 

      When other symbols are encountered, we just push into the stack. If the stack is empty, return "/".

    After we coping with the string, we find that we want to pop the element from front to end. Thus, we use list structure. 

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         list<string> li;
     5         if(path.size() == 0) return "";
     6         
     7         int index = 0;
     8         while(index < path.size()){
     9             int comp = index; //judge whether there are elements between two seperators
    10             string temp;
    11             while(index < path.size() && path[index] != '/'){//extract elements between two seperators
    12                 temp += path[index++];
    13             }//index < path.size() is very important!! to avoid unlimited iteration
    14             
    15             if(index != comp){
    16                 if(temp == ".."){
    17                     if(!li.empty()) li.pop_back();
    18                 }
    19                 else if(temp == ".") continue;
    20                 else li.push_back(temp);
    21             }
    22             index++;
    23         }
    24         string result;
    25         while(!li.empty()){
    26             result += "/" + li.front();
    27             li.pop_front();
    28         }
    29         if(result.size() == 0) return "/";
    30         return result;
    31     }
    32 };
  • 相关阅读:
    C# IP地址字符串和数值转换
    Xstream序列化实体
    异步线程及同步控制
    XML序列化与反序列化(转)
    C# Webserice 代理生成工具(WSDL)
    ASP.NET(C#)图片加文字、图片水印(转)
    异步导致UI句柄增加的解决办法
    终于找到WinForm自定义控件不能拖到IDE设计器容器的办法
    C# PropertyGrid控件应用心得(转载)
    GDI_图片半透明效果示例
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4756424.html
Copyright © 2011-2022 走看看