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 : "/"; };
当你看清人们的真相,于是你知道了,你可以忍受孤独