每日一恋 - LeetCode 71. Simplify Path(简化路径)

题目描述

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,

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

边界情况:

  • 你是否考虑了 路径 = “/../” 的情况?
    在这种情况下,你需返回 “/” 。
  • 此外,路径中也可能包含多个斜杠 ‘/’ ,如 “/home//foo/” 。
    在这种情况下,你可忽略多余的斜杠,返回 “/home/foo” 。

分析

思路其实很简单,切割字符串后,取出每一个路径名,如果是空,跳过;如果路径中没有出现.,那么压入栈;如果包含.,就看有几个.,一个表示当前目录,无意义,三个以上根据题目要求也要压入栈。只有..一种情况需要pop,在pop之前还要检查栈中是否有元素,没有元素也不需要进行操作。最后将剩余的路径用/连接起来即可。

public String simplifyPath(String path) {

    Stack<String> stack = new Stack<String>();
    for (String s : path.split("/")) {
        if (s.isEmpty())
            continue;

        if (s.contains(".")) {
            if (s.equals(".")) {
                continue;
            }

            if (s.equals("..")) {
                if (stack.isEmpty()) continue;
                stack.pop();
            }
            else {
                stack.push(s);
            }
        }
        else {
            stack.push(s);
        }
    }

    StringBuilder sb = new StringBuilder();
    for (String s : stack) {
        sb.append("/" + s);
    }

    return sb.length() == 0 ? "/" : sb.toString();
}

以下是shpolsky的解决方法,与我的思路是相同的,但很简洁。

public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>();
    Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));
    for (String dir : path.split("/")) {
        if (dir.equals("..") && !stack.isEmpty()) stack.pop();
        else if (!skip.contains(dir)) stack.push(dir);
    }
    String res = "";
    for (String dir : stack) res = "/" + dir + res;
    return res.isEmpty() ? "/" : res;
}

如果文章里有说得不对的地方请前辈多多指正~ 与君共勉~

猜你喜欢

转载自blog.csdn.net/smartnijun/article/details/81779080