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"

    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     string simplifyPath(string path) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         stack<string> Stack;
     5         while(true){
     6             if(path == "/")
     7                 break;
     8             int index = path.find('/', 1);
     9             string tmp;
    10             if(index == -1){
    11                 tmp = path.substr(1);
    12                 path = "/";
    13             }
    14             else{
    15                 tmp = path.substr(1, index-1);
    16                 path = path.substr(index);
    17             }
    18             if(tmp == "")
    19                 continue;
    20             else if(tmp == ".."){
    21                 if(!Stack.empty())
    22                     Stack.pop();
    23                 else
    24                     continue;
    25             }
    26             else if(tmp != ".")   
    27                 Stack.push(tmp);
    28         }
    29         string result = "";
    30         if(Stack.empty())
    31             return "/";
    32         while(!Stack.empty()){
    33             result = "/" + Stack.top() + result;
    34             Stack.pop();
    35         }
    36         return result;
    37     }
  • 相关阅读:
    24、合并两个有序链表
    23、反转链表
    22、删除链表的倒数第N个节点
    21、删除链表中的节点
    18、实现strStr()
    17、字符串转换整数 (atoi)
    15、有效的字母异位词
    16、验证回文字符串
    14、字符串中的第一个唯一字符
    mybatis入门(七)----延迟加载
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3442496.html
Copyright © 2011-2022 走看看