文章目录
  1. 1. Simplify Path
    1. 1.1. My solution

Simplify Path

Question:Given an absolute path for a file (Unix-style), simplify it.

For example,
path = /home/ => /home
path = /a/./b/../../c/ => /c

Situation Meaning Solution
/.. 返回上级目录 若stack不空,stack.pop()
/. 留在本目录 无操作
/ 多余的slash 无操作
other 有效目录名 入栈

My solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static String soluition(String path) {
String[] unit = path.split("/");
StringBuffer line = new StringBuffer();
Stack<String> stack = new Stack<String>();
for (int i = 0; i < unit.length; i++) {
if (!unit[i].equals("")) {
if (unit[i].equals(".")) {
continue;
}else if (unit[i].equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
stack.pop();
}
}else {
stack.push("/");
stack.push(unit[i]);
}
}
}
if (stack.isEmpty()) {
return "/";
}else {
while (!stack.isEmpty()) {
line.insert(0, stack.pop());
}
return line.toString();
}
}
文章目录
  1. 1. Simplify Path
    1. 1.1. My solution