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 : "/";
};

posted @ 2021-06-26 19:06  牛有肉  阅读(48)  评论(0编辑  收藏  举报