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/../../c/", => "/c"

    click to show corner cases.

    Solution:

     1 public class Solution {
     2     public String simplifyPath(String path) {
     3         if (path.isEmpty()) return "";
     4 
     5         StringBuilder builder = new StringBuilder();
     6         builder.append('/');
     7         int index = 1;
     8         while (index<path.length()){
     9             //get the next directory command.
    10             int next = index;
    11             while (next<path.length() && path.charAt(next)!='/') next++;
    12             String dir = path.substring(index,next);
    13             if (dir.equals(".") || dir.isEmpty()){
    14                 index = next+1;
    15                 continue;
    16             } else if (dir.equals("..")){
    17                 pathBack(builder);
    18             } else {
    19                 builder.append(dir);
    20                 builder.append('/');
    21             }
    22             index = next+1;
    23         }
    24 
    25         if (builder.length()>1 && builder.charAt(builder.length()-1)=='/')
    26             builder.deleteCharAt(builder.length()-1);
    27         return builder.toString();
    28     }
    29 
    30     public void pathBack(StringBuilder builder){
    31         builder.deleteCharAt(builder.length()-1);
    32         while (builder.length()>0 && builder.charAt(builder.length()-1)!='/')
    33             builder.deleteCharAt(builder.length()-1);
    34         if (builder.length()==0) builder.append('/');
    35     }
    36 }
  • 相关阅读:
    java中的单例模式
    数组的冒泡排序
    2019年总结—即将而立之年的90后
    圣诞节开启博客之旅
    分布式多线程的Lock示例
    抽象工厂模式
    观察者模式
    建造者模式
    外观模式(Facade)
    模板方法模式
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4200266.html
Copyright © 2011-2022 走看看