71.简化路径

2020-03-01  本文已影响0人  最尾一名

原题

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('/');
};

复杂度

上一篇 下一篇

猜你喜欢

热点阅读