Simple solution with stack


  • 0
    L
    function simplifyPath(path) {
        if (!path || !path.length) {
            return '';
        }
        
        var stack = [];
        
        path.split('/').forEach(p => {
            p = p.trim();
            if (!p.length) {
                return;
            }
            if (p === '.') {
                return;
            }
            if (p === '..') {
                return stack.pop();
            }
            stack.push(p);
        });
        
        return '/' + stack.join('/');
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.