Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
[分析] 思路很简单,遇到“.”跳过,遇到“..”删除其前面一级目录,使用堆栈来删除前一级目录的想法很妙(要是我自己想出来就好了~)。 另外分割字符串来处理的思路也要用心体会,联系reverse-words-in-a-string 一题:
https://leetcode.com/problems/reverse-words-in-a-string/
public String simplifyPath(String path) {
if (path == null || path.length() == 0)
return path;
String[] dirs = path.split("/");
LinkedList<String> stack = new LinkedList<String>();
for (String dir : dirs) {
if (dir.isEmpty() || dir.equals("."))
continue;
else if (dir.equals("..")) {
if (!stack.isEmpty())
stack.pop();
} else {
stack.push(dir);
}
}
if (stack.isEmpty()) {
return "/";
}
StringBuilder newpath = new StringBuilder();
while (!stack.isEmpty()) {
newpath.insert(0,"/" + stack.pop());
}
return newpath.toString();
}
分享到:
相关推荐
javascript js_leetcode题解之71-simplify-path.js
c c语言_leetcode题解之0071_simplify_path.zip
leetcode双人赛71.-Simplify-Path-Leetcode 给定一个字符串路径,它是 Unix 样式文件系统中文件或目录的绝对路径(以斜杠“/”开头),将其转换为简化的规范路径。 在 Unix 风格的文件系统中,句点 '.' 指的是当前...
- Simplify Path: 给定一个表示文件系统的路径,请实现一个方法,以简化这个路径。 - Edit Distance: 给定两个单词word1和word2,计算将word1转换为word2所使用的最少操作数。 - Set Matrix Zeroes: 给定一个m×n的...
# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...
leetcode中国 我自己的leetcode刷题记录 ###[20150920] Valid Palindrome Implement strStr() String to Integer ...Simplify Path,字符串处理,stack Length of Last Word,字符串处理.细节题 Rever
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 UNIX-style file ...
LeetCode第71题的全称是“Simplify Path”,该题目要求我们编写一个程序,将输入的复杂路径字符串简化为最基础的目录序列。例如,输入的路径可能是"/a/./b/../../c/",输出应该是"/c"。这个问题主要考察的是对字符串...
在本压缩包中,主题聚焦于C++编程基础与LeetCode算法题目的解法,特别是针对LeetCode第71题“简化路径”(Simplify Path)的探讨。这道题目旨在检验开发者的路径解析能力,涉及到字符串处理和栈的数据结构应用。让...