原题
https://leetcode-cn.com/problems/simplify-path/
解题思路
自动机
代码
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
path = path.replace(/\/\//g, '/');
const pathArr = path.split('/').slice(1);
const res = [];
while (pathArr.length) {
const current = pathArr.shift();
switch(current) {
case '.':
break;
case '':
break;
case '..':
if (res.length) {
res.pop();
}
break;
default:
res.push(current);
break;
}
}
return '/' + res.join('/');
};
复杂度
- 时间复杂度 O(N)
- 空间复杂度 O(N)
网友评论