leetcode 71. Simplify Path(简化路径)

该博客主要讨论了如何在Linux风格的文件系统中对绝对路径进行简化,转化为规范路径。通过解析输入的路径字符串,处理'.'、'..'和连续的'/',将路径转化为不含冗余元素的形式。博主提供了两种不同的Java实现方式,一种使用栈,另一种用数组模拟栈,这两种方法都有效地实现了路径简化。

Given a string path, which is an absolute path (starting with a slash ‘/’) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period ‘.’ refers to the current directory, a double period ‘…’ refers to the directory up a level, and any multiple consecutive slashes (i.e. ‘//’) are treated as a single slash ‘/’. For this problem, any other format of periods such as ‘…’ are treated as file/directory names.

The canonical path should have the following format:

The path starts with a single slash ‘/’.
Any two directories are separated by a single slash ‘/’.
The path does not end with a trailing ‘/’.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period ‘.’ or double period ‘…’)
Return the simplified canonical path.

Example 1:

Input: path = “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:

Input: path = “/…/”
Output: “/”
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:

Input: path = “/home//foo/”
Output: “/home/foo”

简单来说就是linux下路径简化问题。

思路:
路径简化有以下几种情况:

  1. 多个" / “可简化为一个” / "。
  2. " … “表示回到上一路径,比如”/home/leetcode/…“就是”/home", 这相当于把上一个leetcode给pop出来了。
  3. “.“表示当前路径,比如”/home/leetcode/.”, 那就是"/home/leetcode",可以看到"."没有任何作用,可以跳过
  4. 如果路径为空,认为就在根目录下,即" / "。

根据上面的情况,可以用" / “来split路径,提取split出来的字符串,然后用”/“连接这些字符串。
其中,”.“的字符串直接跳过,”…“就把前一个字符串pop掉,空字符串跳过(多个”/"简化为1个)。

    public String simplifyPath(String path) {
   
   
        Stack<String> stack = new Stack();
        StringBuilder result = new StringBuilder();
        String[
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值