栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode - Medium - 71

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode - Medium - 71

  • 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”

Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: path = “/a/./b/…/…/c/”

Output: “/c”

Constraints:

  • 1 <= path.length <= 3000

  • path consists of English letters, digits, period '.', slash '/' or '_'.

  • path is a valid absolute Unix path.

[](()Analysis


[](()Submission


import java.util.LinkedList;

public class SimplifyPath {

// 方法一:我写的

public String simplifyPath(String path) {

LinkedList dirs = new LinkedList<>();

for (int p1 = 0, p2 = 1; p2 <= path.length(); p2++) {

if (p2 == path.length() || path.charAt(p2) == ‘/’) {

String dir = path. 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 substring(p1 + 1, p2);

p1 = p2;

if (dir.equals(“”) || dir.equals(“.”))

continue;

if (dir.equals(“…”)) {

if (!dirs.isEmpty())

dirs.removeLast();

} else {

dirs.add(dir);

}

}

}

StringBuilder sb = new StringBuilder();

dirs.stream().forEach(dir -> sb.append(“/”).append(dir));

return sb.length() == 0 ? “/” : sb.toString();

}

// 方法二:别人写的,写得更简洁

public String simplifyPath2(String path) {

LinkedList list = new LinkedList<>();

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/858052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号