[LeetCode]--71. 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.Corner Cases:

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;
    }
目录
相关文章
|
存储
LeetCode 329. Longest Increasing Path in a Matrix
给定一个整数矩阵,找出最长递增路径的长度。 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
45 0
LeetCode 329. Longest Increasing Path in a Matrix
|
Unix Python
LeetCode 71. Simplify Path
给定文件的绝对路径(Unix下的路径)字符串,简化此字符串。
63 0
LeetCode 71. Simplify Path
LeetCode 64. Minimum Path Sum
给定m x n网格填充非负数,找到从左上到右下的路径,这最小化了沿其路径的所有数字的总和。 注意:您只能在任何时间点向下或向右移动。
69 0
LeetCode 64. Minimum Path Sum
LeetCode 112 Path Sum(路径和)(BT、DP)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50569025 翻译 给定一个二叉树root和一个和sum, 决定这个树是否存在一条从根到叶子的路径使得沿路所有节点的和等于给定的sum。
735 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2

热门文章

最新文章