• 71. Simplify Path


     


    Given an absolute path for a file (Unix-style), simplify it. 

    For example,
    path = "/home/", => "/home"
    path = "/a/./b/../../c/", => "/c"
    path = "/a/../../b/../c//.//", => "/c"
    path = "/a//b////c/d//././/..", => "/a/b/c"

    In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

    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".
     
     
    思路:
    利用stack
    如果是..   返回上一层目录----》弹栈
    如果是. 或者空字符 啥也不操作
    如果是字母:进入字母目录---》》 把字母压栈
     
     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         string res,temp;
     5         stack<string> mystack ;
     6         stringstream  ss(path);
     7         while(getline(ss,temp,'/')){
     8             if(temp==".."){
     9                 if(mystack.size()!=0)
    10                     mystack.pop();
    11             }
    12             else if(temp=="."||temp=="") 
    13                 continue;
    14             else
    15                 mystack.push(temp);
    16                 
    17         }
    18          while (!mystack.empty()){
    19             res="/"+mystack.top()+res;
    20             mystack.pop();
    21             }
    22         
    23          return res.empty() ? "/" : res;
    24 
    25     }
    26    
    27 };
  • 相关阅读:
    HDU 2795
    HDU 1394
    HDU 1754
    HDU 1166
    SDOI 2006
    HDU 1423
    HDU 1561
    centos7.4 搭建zabbix-server 3.4.5
    vim 简单笔记
    jdk环境并配置环境变量
  • 原文地址:https://www.cnblogs.com/zle1992/p/10233270.html
Copyright © 2020-2023  润新知