Skip to content

Commit cbe4eb5

Browse files
LeetCode第71题
1 parent 1a82ef5 commit cbe4eb5

40 files changed

+152
-58
lines changed

.idea/workspace.xml

Lines changed: 85 additions & 58 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package leetcode.stack;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Stack;
6+
7+
/**
8+
* <p>
9+
* 以 Unix 风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。
10+
在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分
11+
请注意,返回的规范路径必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。最后一个目录名(如果存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。
12+
13+
输入:"/a/./b/../../c/"
14+
输出:"/c"
15+
16+
输入:"/a/../../b/../c//.//"
17+
输出:"/c"
18+
* </p>
19+
*
20+
* @author jwzhao
21+
* @version 1.0
22+
* @date 2019/3/19 09:48
23+
*/
24+
public class LeetCode71 {
25+
26+
public static void main(String[] args) {
27+
LeetCode71 leetCode71 = new LeetCode71();
28+
String path = "/a//b////c/d//././/..";
29+
System.out.println(leetCode71.simplifyPath(path));
30+
}
31+
32+
public String simplifyPath(String path) {
33+
if (path == null || "".equals(path)){
34+
return "";
35+
}
36+
Stack<String> stack = new Stack<>();
37+
// 以/ 拆分字符串
38+
String[] paths = path.split("/");
39+
40+
// paths = ["a",".","b","..","..","c"]
41+
for (int i=0;i<paths.length;i++){
42+
String p = paths[i];
43+
if ("".equals(p) || ".".equals(p)){
44+
continue;
45+
}
46+
if ("..".equals(p)){
47+
if (!stack.empty()){
48+
stack.pop();
49+
}
50+
}else{
51+
stack.push(p);
52+
}
53+
}
54+
List<String> list = new ArrayList<>();
55+
while (!stack.empty()){
56+
list.add(stack.pop());
57+
}
58+
StringBuffer buffer = new StringBuffer("/");
59+
for (int i=list.size()-1;i>=0;i--){
60+
buffer.append(list.get(i));
61+
if (i>0){
62+
buffer.append("/");
63+
}
64+
}
65+
return buffer.toString();
66+
}
67+
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)