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();
        }
    }
    
  • 相关阅读:
    掌门教育首通和续费文案整理
    python upload file遇到的坑,整理如下
    测试难题(转)
    敏捷测试与传统测试的区别
    质量体系
    幂等校验
    Charles常用功能整理
    测试难题
    敏捷测试与传统测试的区别
    质量体系
  • 原文地址:https://www.cnblogs.com/acbingo/p/9369148.html
Copyright © 2011-2022 走看看