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();
        }
    }
    
  • 相关阅读:
    java.sql.SQLSyntaxErrorException: ORA-01722: 无效数字
    Lambda表达式详解
    MAC JDK 卸载方法(彻底卸载)
    JAVA final关键字
    JAVA访问权限
    JAVA重写
    JAVA继承
    单例设计模式---懒汉式和饿汉式
    JAVA构造块和静态代码块
    Java static关键字
  • 原文地址:https://www.cnblogs.com/acbingo/p/9369148.html
Copyright © 2011-2022 走看看