Simplify Path

来源:互联网 发布:剑三代练淘宝下单好吗 编辑:程序博客网 时间:2024/06/05 11:17

题目:

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".
思路:

当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。

当遇到"/./"则表示是本级目录,无需做任何特殊操作。

当遇到"//"则表示是本级目录,无需做任何操作。

当遇到其他字符则表示是文件夹名,无需简化。

当字符串是空或者遇到”/../”,则需要返回一个"/"。当遇见"/a//b",则需要简化为"/a/b"。

当字符串为空或者为".",不做任何操作。当字符串不为"..",则将字符串入list。当字符串为"..", 则删除最后一个(返回上级目录)。

[java] view plain copy
  1. public class Solution {  
  2.     public static String simplifyPath(String path) {  
  3.         String strs[] = path.split("/");  
  4.         LinkedList<String> list = new LinkedList<>();  
  5.         for (String str : strs) {  
  6.             if (str.equals("..") && !list.isEmpty()) {  
  7.                 list.removeLast();  
  8.             } else if (!str.equals(".") && !str.equals("") && !str.equals("..")) {  
  9.                 list.add(str);  
  10.             }  
  11.         }  
  12.   
  13.         StringBuilder result = new StringBuilder();  
  14.         while (!list.isEmpty()) {  
  15.             result.append("/");  
  16.             result.append(list.removeFirst());  
  17.         }  
  18.         if (result.length() == 0) {  
  19.             return "/";  
  20.         }  
  21.         return result.toString();  
  22.     }  
  23. }  
0 0
原创粉丝点击