/** * https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150 * @param {string} path * @return {string} */ const simplifyPath = function (path) { }; /* 首先通过'/'来分割path,我们会得到如下的字符串,目录名,"."当前目录,".."上级目录,如果遇到的是文件名, 就把文件名压入栈stack中,如果遇到的是.或者空字符无需做任何操作,如果遇到的是".."则需要把当前stack栈顶 的目录弹出表示跳转到上级目录 */ function f1(path) { const paths = path.split('/'); // 使用/来分割路径 const stack = []; // 利用栈来处理路径 for (const p of paths) { // if (p === '.' || p === '') continue; // if (p === '..') { // // 返回到上级目录 // if (stack.length) stack.pop(); // continue; // } // stack.push(p); // 优化上面分支,实际上我们要做的就两件事情,第一:如果是".."表明要跳转到上级目录,如果一个合规 // 的目录名,就应该压入栈中 if (p === '..') { if (stack.length) stack.pop(); } else if (p !== '' && p !== '.') { stack.push(p); } } return `/${stack.join('/')}`; }