zoukankan      html  css  js  c++  java
  • Leetcode 71 简化路径

      . 和 / 的可能组合过多时,分开处理。先按 / 分割字符串,再处理 . 。

      JAVA:

     public final String simplifyPath(String path) {
            int len = path.length();
            StringBuilder sb = new StringBuilder();
            Stack<String> stack = new Stack();
            for (int i = 0; i < len; i++) {
                if (path.charAt(i) == '/') {
                    while (i < len && path.charAt(i) == '/') i++;
                    int begin = i;
                    while (i < len && path.charAt(i) != '/') i++;
                    int end = i;
                    if (end > begin) stack.push(path.substring(begin, end));
                    i--;
                }
            }
            Stack<String> reStack = new Stack<String>();
            for (int i = 0; i < stack.size(); i++) {
                String node = stack.get(i);
                if (".".equals(node) && reStack.size() > 0) continue;
                else if ("..".equals(node)) {
                    if (reStack.size() > 0) reStack.pop();
                } else reStack.push(node);
            }
            for (int i = 0; i < reStack.size(); i++) sb.append("/" + reStack.get(i));
            return sb.length() > 0 ? sb.toString() : "/";
        }

      JS:

    /**
     * @param {string} path
     * @return {string}
     */
    var simplifyPath = function (path) {
        let stack = [], reStack = [], len = path.length, re = "";
        for (let i = 0; i < len; i++) {
            if ("/" == path.charAt(i)) {
                while (i < len && path.charAt(i) == "/") i++;
                let begin = i;
                while (i < len && path.charAt(i) != "/") i++;
                if (i > begin) stack.push(path.substring(begin, i));
                i--;
            }
        }
        for (let i = 0; i < stack.length; i++) {
            let node = stack[i];
            if (node == ".") continue;
            if (node == "..") {
                if (reStack.length > 0) reStack.pop();
            } else reStack.push(node);
        }
        for (let i = 0; i < reStack.length; i++) re += "/" + reStack[i];
        return re.length > 0 ? re : "/";
    };

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    低压配电系统接地方式
    在MFC中添加用户自定义消息
    二维数组指针(百度)
    2009-08-12 17:19 16进制浮点数与十进制的转化 (转载)
    UCOS 中的中断处理
    转:智能卡测试操作系统技术
    转:ADO,OLEDB,ODBC,DAO的区别
    VC引用动态库
    VC引用静态库
    windows下查看静态库和动态库的导出函数
  • 原文地址:https://www.cnblogs.com/niuyourou/p/14938758.html
Copyright © 2011-2022 走看看