zoukankan      html  css  js  c++  java
  • 71. 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".

    链接:https://leetcode.com/problems/simplify-path/#/description

    5/27/2017

    9ms. 86%

    注意的问题:

    1. LinkedList当作stack的push, pop:操作在链表头。list.push(1), list.push(2)画图表示出来为2->1,所以此时list.get(0)返回的应该是2。不要想当然认为是从尾巴开始加,毕竟对于链表最方便的操作就是在表头。

    2. 如果记不住前一点,就用removeLast, addLast来表示好了

    3. 26行注意判断是否返回的是root

     1 public class Solution {
     2     public String simplifyPath(String path) {
     3         if (path == null || path.length() == 0 || path.equals("")) {
     4             return "";
     5         }
     6         LinkedList<String> list = new LinkedList<String>();
     7         String[] parts = path.split("/");
     8 
     9         for (int i = 0; i < parts.length; i++) {
    10             if (parts[i].equals("") || parts[i].equals(".")) continue;
    11             else if (parts[i].equals("..")) {
    12                 if (list.isEmpty()) continue;
    13                 else {
    14                     list.removeLast();
    15                 }
    16             } else {
    17                 list.addLast(parts[i]);
    18             }
    19         }
    20         StringBuilder sb = new StringBuilder();
    21         int size = list.size();
    22         for (int i = 0; i < size; i++) {
    23             sb.append("/");
    24             sb.append(list.get(i));
    25         }
    26         return sb.length() == 0? "/": sb.toString();
    27     }
    28 }

    更多讨论:

    https://discuss.leetcode.com/category/79/simplify-path

  • 相关阅读:
    连续多步骤业务流程的暂停、中断和恢复
    什么是XML
    泛型擦除和反射配置文件
    类加载器和反射
    网络安全协议(二)
    网络通信协议(一)
    多线程之线程安全
    JAVA之线程池
    JAVA之多线程
    2020/8/1 JAVA之IO流(四)
  • 原文地址:https://www.cnblogs.com/panini/p/6914959.html
Copyright © 2011-2022 走看看