Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
public String simplifyPath(String path) { String[] paths = path.split("\\/+"); Stack<String> stack = new Stack<>(); for(String p:paths) { if(p.isEmpty() || p.equals(".")) continue; if(p.equals("..")) { if(!stack.isEmpty()) stack.pop(); } else { stack.push(p); } } if(stack.isEmpty()) return "/"; String s = ""; while(!stack.isEmpty()) { s = "/"+stack.pop()+s; } return s; }
相关推荐
本篇文章将详细解读 LeetCode 中题号为 71 的问题——简化路径,并给出使用 JavaScript 解决该问题的代码示例。 问题描述: 在计算机文件系统中,路径是由一系列的目录组成,路径中的每个部分都是由斜杠(‘/’)隔...
在这个上下文中,"0071-simplify-path"指的是第71题的简化路径问题。简化路径是一个常见的文件系统操作问题,在许多操作系统中,路径名可以使用相对路径或绝对路径来表示文件或目录的位置。简化路径的意思是将给定的...
leetcode双人赛71.-Simplify-Path-Leetcode 给定一个字符串路径,它是 Unix 样式文件系统中文件或目录的绝对路径(以斜杠“/”开头),将其转换为简化的规范路径。 在 Unix 风格的文件系统中,句点 '.' 指的是当前...
- Simplify Path: 给定一个表示文件系统的路径,请实现一个方法,以简化这个路径。 - Edit Distance: 给定两个单词word1和word2,计算将word1转换为word2所使用的最少操作数。 - Set Matrix Zeroes: 给定一个m×n的...
leetcode中国 我自己的leetcode刷题记录 ###[20150920] Valid Palindrome Implement strStr() String to Integer ...Simplify Path,字符串处理,stack Length of Last Word,字符串处理.细节题 Rever
71. Simplify Path** https://leetcode.com/problems/simplify-path/ 题目描述 Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. In a...
# [LeetCode](https://leetcode.com/problemset/algorithms/)  [![License]...
LeetCode第71题的全称是“Simplify Path”,该题目要求我们编写一个程序,将输入的复杂路径字符串简化为最基础的目录序列。例如,输入的路径可能是"/a/./b/../../c/",输出应该是"/c"。这个问题主要考察的是对字符串...
在本压缩包中,主题聚焦于C++编程基础与LeetCode算法题目的解法,特别是针对LeetCode第71题“简化路径”(Simplify Path)的探讨。这道题目旨在检验开发者的路径解析能力,涉及到字符串处理和栈的数据结构应用。让...