71. Simplify Path

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

Example

"/home/", => "/home"

"/a/./b/../../c/", => "/c"

Challenge 
  • 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      /* 归下类的话,有四种字符串:
 3         1. "/":为目录分隔符,用来分隔两个目录。
 4         2. ".":当前目录
 5         3. "..":上层目录
 6         4. 其他字符串:目录名
 7 
 8         简化的核心是要找出所有的目录,并且如果遇到"..",需要删除上一个目录。
 9      */
10         public  String simplifyPath(String path) {
11         if (path == null || path.length() == 0) return path;
12 
13         String[] subPath = path.split("/");
14         Stack<String> stack = new Stack<>();
15         for (int i = 0; i < subPath.length; i++) {
16             String str = subPath[i];
17             if (!(str.equals(".") || str.isEmpty())) { // for . and empty string, we do nothing.
18                 if (str.equals("..")) { // we need to remove one upper directory
19                     if (!stack.isEmpty()) {
20                         stack.pop();
21                     }
22                 } else {
23                     stack.push("/" + str);
24                 }
25             }
26         }
27         
28         StringBuilder sb = new StringBuilder();
29         for (String str : stack) {
30             sb.append(str);
31         }
32         return sb.length() == 0 ? "/" : sb.toString();
33     }
34 
35 }

 如果这题改一下

给一个current path, 给一个新的path, 通过cd在当前path执行新的path,问最后的path是什么

这里需要区分新的path是绝对路径还是相对路径,如果新的path是绝对路线,直接不要用当前的path, 如果新的path是相对路径,那么直接把新的path append到当前path,然后再做同样的处理。 

def change_path(current: str, changed: str) -> str:
    if not changed:
        return current
    if changed[0] == "/":
        current = ""

    path = []
    
    for segment in (current + "/" + changed).split("/"):
        if segment == "..":
            if path:
                path.pop()
        elif segment and segment != ".":
            path.append(segment)

    return "/" + "/".join(path)

 

posted @ 2016-07-17 01:02  北叶青藤  阅读(218)  评论(0)    收藏  举报