Simplify path

Problem description

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

Examples

1
2
3
Example 1:
Input : "/home/"
Output : “/home”
1
2
3
Example 2:
Input : "/a/../../b/../c//.//"
Output : “/c”
1
2
3
Example 3:
Input : "/a/./b/../../c/"
Output : “/c”

Solution

  边界情况考虑好,当为/../,即已经访问到根目录时,再往前是无法访问的。返回“/”

Code

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
 class Solution {

public String simplifyPath(String path) {
String[] strings = path.split("/", 0);
Stack<String> stack = new Stack<>();
for (int i = 0; i < strings.length; i++) {
if ( ".".equals(strings[i]) || "".equals(strings[i])) {
continue;
} else if ("..".equals(strings[i])) {
if (!stack.empty()) {
stack.pop();
}
} else {
stack.push(strings[i]);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, stack.pop());
sb.insert(0, '/');
}
if (sb.length() == 0) {
sb.append('/');
}
return sb.toString();
}

}
文章目录
  1. 1. Problem description
    1. 1.1. Given an absolute path for a file (Unix-style), simplify it.
  2. 2. Examples
  3. 3. Solution
  4. 4. Code
|