且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode]--71. Simplify Path

更新时间:2021-10-23 19:19:33

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”.

这个题目重点就是要理解它的意思,如果是一个点 . 那就是当前路径,不管,如果是两个点 .. 那就是当前路径的上一个目录。这样我们用栈来表示的话,就是如下所示

path:"/a/./b/../../c/"

split:"a",".","b","..","..","c"

stack:push(a), push(b), pop(b), pop(a), push(c) --> c

明白这个之后就一目了然了,就是注意返回的时候如果是”/”或者”/../”这种情形就行。

public String simplifyPath(String path) {
        String res = "";
        String[] arrs = path.split("/");
        Stack<String> s = new Stack<String>();

        for (int i = 0; i < arrs.length; i++) {
            if (arrs[i].equals("")) {
                continue;
            }
            if (!arrs[i].equals(".") && !arrs[i].equals("..")) {
                s.push(arrs[i]);
            }
            if (arrs[i].equals("..") && !s.isEmpty()) {
                s.pop();
            }
        }
        if (s.isEmpty())
            return "/";
        while (!s.isEmpty())
            res = "/" + s.pop() + res;
        return res;
    }

另一种链表的做法

public String simplifyPath1(String path) {
        String result = "/";
        String[] stubs = path.split("/+");
        ArrayList<String> paths = new ArrayList<String>();
        for (String s : stubs){
            if(s.equals("..")){
                if(paths.size() > 0){
                    paths.remove(paths.size() - 1);
                }
            }
            else if (!s.equals(".") && !s.equals("")){
                paths.add(s);
            }
        }
        for (String s : paths){
            result += s + "/";
        }
        if (result.length() > 1)
            result = result.substring(0, result.length() - 1);
        return result;
    }