zoukankan      html  css  js  c++  java
  • [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();
        }
    }
    
  • 相关阅读:
    结对编程之附加题:单元测试
    机器学习第二次作业
    第一次作业
    机器学习第二次作业
    机器学习第一次个人作业
    软工实践个人总结
    第08组 Beta版本演示
    第08组 Beta冲刺(5/5)
    第08组 Beta冲刺(4/5)
    第08组 Beta冲刺(3/5)
  • 原文地址:https://www.cnblogs.com/acbingo/p/9369148.html
Copyright © 2011-2022 走看看