[leetcode] 71. 简化路径

71. 简化路径

维护一个栈,当出现.时不做操作,出现..时栈中弹走一个元素

最后从头遍历栈输出即可

注意,文件名可能是千奇百怪的,超过两个.(比如...)可认作文件名

注意,
不要相信playgroud提供的main函数!
不要相信playgroud提供的main函数!
不要相信playgroud提供的main函数!

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<>();
        int i = 0;
        while (i < path.length()) {
            while (i < path.length() && path.charAt(i) == '/') i++;
            if (i >= path.length()) break;
            if (path.charAt(i) == '.') {
                if (i + 1 >= path.length()) {
                    break;
                }
                if (path.charAt(i + 1) == '/') {
                    // ./
                    i++;
                    continue;
                }
                if (path.charAt(i + 1) == '.') {
                    if (i + 2 >= path.length() || path.charAt(i + 2) == '/') {
                        // ../
                        i += 2;
                        if (!stack.isEmpty()) {
                            stack.pop();
                        }
                        continue;
                    }
                }
            }
            // is word
            StringBuilder word = new StringBuilder();
            while (i < path.length() && path.charAt(i) != '/') {
                word.append(path.charAt(i));
                i++;
            }
            stack.push(word.toString());

        }

        StringBuilder ans = new StringBuilder();
        if (stack.isEmpty()) {
            return "/";
        }
        for (String s : stack) {
            ans.append("/").append(s);
        }
        return ans.toString();
    }
}

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9369148.html
今日推荐