zoukankan      html  css  js  c++  java
  • [LeetCode] Simplify Path

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

    For example,
    path = "/home/", => "/home"
    path = "/a/./b/http://www.cnblogs.com/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".
    用栈来做
     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         stack<string> s;
     7         string str;
     8         for(int i = 0; i < path.size(); i++)
     9         {
    10             if (path[i] == '/')
    11             {
    12                 if (str == "..")
    13                 {
    14                     if (!s.empty())
    15                         s.pop();
    16                 }
    17                 else if (str != "." && str != "")
    18                 {
    19                     s.push(str);
    20                 }
    21 
    22                 str = "";
    23             }
    24             else
    25             {
    26                 str += path[i];
    27             }
    28         }
    29         
    30         if (str == "..")
    31         {
    32             if (!s.empty())
    33                 s.pop();
    34         }
    35         else if (str != "." && str != "")
    36             s.push(str);
    37         
    38         if (s.empty())
    39             return "/";
    40         
    41         string ret;
    42         while(!s.empty())
    43         {
    44             ret = "/" + s.top() + ret;
    45             s.pop();
    46         }
    47         
    48         return ret;
    49     }
    50 };
  • 相关阅读:
    文件的操作
    encode,decode,str,bytes
    字符串操作
    suse12安装mysql8.16
    VMware配置共享磁盘安装RAC
    Linux过滤文本并显示过滤文字的上下文
    Linux服务器卸载mysql指南
    oracle 各版本各日志存放位置
    impdp按用户导入
    数据泵expdp定时备份
  • 原文地址:https://www.cnblogs.com/chkkch/p/2778005.html
Copyright © 2011-2022 走看看