当前位置: 面试刷题>> 简化路径(经典算法150题)


题目描述

在文件系统中,路径通常由斜杠(/)分隔的目录或文件名组成。例如,"/home/user/document.txt" 是一个表示文件系统中文件路径的字符串。给定一个这样的路径字符串,我们需要编写一个函数来简化它。

路径简化的规则如下:

  1. 路径中的多余斜杠(//)需要被替换为单个斜杠(/)。
  2. 路径中的点(.)表示当前目录,因此应该被删除。
  3. 路径中的点(..)表示上一级目录,因此需要与前一个目录名(如果有的话)抵消。

注意:

  • 返回的路径应该以斜杠(/)开头,除非它是根目录(即只有单个斜杠)。
  • 路径中不允许有多余的斜杠,也不允许末尾有斜杠(除非它是根目录)。
  • 返回的路径中的目录名称应当按字典序排列(本题目中可忽略此要求,因为它更偏向于文件系统的展示而非路径简化)。

示例

  • 输入: "/a//b////c/d/./././.."
  • 输出: "/a/b/c"

PHP 示例代码

function simplifyPath($path) {
    $stack = [];
    $components = explode('/', trim($path, '/'));

    foreach ($components as $component) {
        if ($component === '.') {
            // 当前目录,跳过
            continue;
        } elseif ($component === '..') {
            // 上一级目录,如果栈不为空则弹出
            array_pop($stack);
        } else {
            // 否则,将组件推入栈中
            $stack[] = $component;
        }
    }

    // 将栈中的组件重新组合为路径
    return '/' . implode('/', $stack);
}

// 示例
echo simplifyPath("/a//b////c/d/./././.."); // 输出: "/a/b/c"

Python 示例代码

def simplifyPath(path):
    stack = []
    components = path.strip('/').split('/')

    for component in components:
        if component == '.' or component == '':
            # 当前目录或空字符串,跳过
            continue
        elif component == '..':
            # 上一级目录,如果栈不为空则弹出
            if stack:
                stack.pop()
        else:
            # 否则,将组件加入栈中
            stack.append(component)

    # 将栈中的组件重新组合为路径
    return '/' + '/'.join(stack)

# 示例
print(simplifyPath("/a//b////c/d/./././.."))  # 输出: "/a/b/c"

JavaScript 示例代码

function simplifyPath(path) {
    const stack = [];
    const components = path.trim('/').split('/');

    for (let component of components) {
        if (component === '.' || component === '') {
            // 当前目录或空字符串,跳过
            continue;
        } else if (component === '..') {
            // 上一级目录,如果栈不为空则弹出
            if (stack.length > 0) {
                stack.pop();
            }
        } else {
            // 否则,将组件推入栈中
            stack.push(component);
        }
    }

    // 将栈中的组件重新组合为路径
    return '/' + stack.join('/');
}

// 示例
console.log(simplifyPath("/a//b////c/d/./././..")); // 输出: "/a/b/c"

在这三个示例中,我们使用了栈(在 PHP 中为数组,在 Python 和 JavaScript 中为栈对象)来模拟路径的简化过程,以符合题目要求的路径简化规则。

推荐面试题