zoukankan      html  css  js  c++  java
  • 面试题33:简化目录路径

    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".
     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         int n = path.size();
     5         stack<string> s;
     6         string dir;
     7         for (int i = 0; i < n; i++) {
     8             if (path[i] == '/') {
     9                 if (!dir.empty()) {
    10                     s.push(dir);
    11                     dir.clear();
    12                 }
    13             } else {
    14                 dir.push_back(path[i]);
    15             }
    16         }
    17         if(!dir.empty()) s.push(dir);
    18 
    19         string res;
    20         int count = 0;
    21         while (!s.empty()) {
    22             string str = s.top();
    23             s.pop();
    24             if (str == ".") {
    25                 continue;
    26             } else if (str == "..") {
    27                 count++;
    28             } else {
    29                 if (count > 0) {
    30                     count--;
    31                 } else {
    32                     res = "/" + str + res;
    33                 }
    34             }
    35         }
    36         if(res.length() == 0) return "/";
    37         return res;
    38     }
    39 };
  • 相关阅读:
    广义表的创建和遍历
    dev c++ Boost库的安装
    NAT模式
    vmware桥接模式
    smb与samba
    利用Linux的Samba服务模拟NT域
    使用samba进行共享文件操作步骤
    安装chrome
    使用虚拟机上网第二步
    TCP协议三次握手过程分析
  • 原文地址:https://www.cnblogs.com/wxquare/p/6912078.html
Copyright © 2011-2022 走看看