【leetcode-71】 简化路径

(1 pass)

以 Unix 风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。

在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。更多信息请参阅:Linux / Unix中的绝对路径 vs 相对路径

请注意,返回的规范路径必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。最后一个目录名(如果存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。

示例 1:

输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。

示例 2:

输入:"/../"
输出:"/"
解释:从根目录向上一级是不可行的,因为根是你可以到达的最高级。

示例 3:

输入:"/home//foo/"
输出:"/home/foo"
解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。

示例 4:

输入:"/a/./b/../../c/"
输出:"/c"

示例 5:

输入:"/a/../../b/../c//.//"
输出:"/c"

示例 6:

输入:"/a//b////c/d//././/.."
输出:"/a/b/c"


路径问题关键:栈的思想
参考解法:
    // 和我的区别是不用判/重复和结尾/,直接split。用split后元素是否为“”判断。更简洁明了
public String simplifyPath(String path) {
        if (path == null || path.length() == 0) {
            return path;
        }
        String[] strs = path.split("/");
        Stack<String> stack = new Stack<>();
        for (String s : strs) {
            if (s.equals("") || s.equals(".")) {
                continue;
            } else if (s.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                } else {
                    continue;
                }
            } else {
                stack.push(s);
            }
        }
        if (stack.isEmpty()) {
            return "/";
        }
        StringBuilder ret = new StringBuilder();
        while (!stack.isEmpty()) {
            ret.insert(0, "/" + stack.pop());
        }
        return ret.toString();
    }

我的:

    public String simplifyPath(String path) {
        StringBuilder sb = new StringBuilder();
        //去掉结尾'/'
        for (int i=path.length()-1;i>0;i--) {
            if (path.charAt(i) != '/') {
                path = path.substring(0,i+1);
                break;
            }
        }
        //去掉重複'/'
        for (int i=0;i<path.length()-1;i++) {
            if (path.charAt(i) != '/' || (path.charAt(i) == '/' && path.charAt(i+1) != '/')) {
                sb.append(path.charAt(i));
            }
        }
        sb.append(path.charAt(path.length()-1));

        String[] a = sb.toString().substring(1).split("/");
        Stack<String> stack = new Stack<>();
        Stack<String> stack1 = new Stack<>();
        for (int i=0;i<a.length;i++) {
            if (a[i].equals(".") || (a[i].equals("..") && stack.isEmpty())) {
                continue;
            } else if (a[i].equals("..")){
                stack.pop();
            } else {
                stack.push(a[i]);
            }
        }
        while(!stack.isEmpty()) {
            stack1.push(stack.pop());
        }
        StringBuilder res = new StringBuilder();
        res.append("/");
        while (!stack1.isEmpty()) {
            res.append(stack1.pop());
            if (!stack1.isEmpty()) {
                res.append("/");
            }
        }
        return res.toString();
    }
原文地址:https://www.cnblogs.com/twoheads/p/10648662.html