简化路径
#栈 #leetcode
目录
思路
- 使用栈:
- 为
.时continue - 为
..时pop
- 为
- 注意
- 栈使用变量简写:
s .split("/")时,不会包含/
- 栈使用变量简写:
代码
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function (path) {
let arr = path.split("/");
console.log("arr:", arr);
let s = [];
for (let item of arr) {
if (item === ".") {
continue;
} else if (item === "..") {
s.pop();
} else if (item) {
s.push(item);
}
}
return `/${s.join("/")}`;
};
技巧:记得 console.log 帮助很快写出代码
