|
6 | 6 | import java.util.LinkedList;
|
7 | 7 | import java.util.Set;
|
8 | 8 |
|
9 |
| -/** |
10 |
| - * 71. Simplify Path |
11 |
| -
|
12 |
| - Given an absolute path for a file (Unix-style), simplify it. |
13 |
| -
|
14 |
| - For example, |
15 |
| - path = "/home/", => "/home" |
16 |
| - path = "/a/./b/../../c/", => "/c" |
17 |
| -
|
18 |
| - Corner Cases: |
19 |
| - Did you consider the case where path = "/../"? |
20 |
| - In this case, you should return "/". |
21 |
| - Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". |
22 |
| - In this case, you should ignore redundant slashes and return "/home/foo". |
23 |
| - */ |
24 | 9 | public class _71 {
|
25 | 10 |
|
26 |
| - public static class Solution1 { |
27 |
| - public String simplifyPath(String path) { |
28 |
| - Deque<String> stack = new LinkedList<>(); |
29 |
| - Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", "")); |
30 |
| - for (String dir : path.split("/")) { |
31 |
| - if (dir.equals("..") && !stack.isEmpty()) { |
32 |
| - stack.pop(); |
33 |
| - } else if (!skipSet.contains(dir)) { |
34 |
| - stack.push(dir); |
| 11 | + public static class Solution1 { |
| 12 | + public String simplifyPath(String path) { |
| 13 | + Deque<String> stack = new LinkedList<>(); |
| 14 | + Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", "")); |
| 15 | + for (String dir : path.split("/")) { |
| 16 | + if (dir.equals("..") && !stack.isEmpty()) { |
| 17 | + stack.pop(); |
| 18 | + } else if (!skipSet.contains(dir)) { |
| 19 | + stack.push(dir); |
| 20 | + } |
| 21 | + } |
| 22 | + String result = ""; |
| 23 | + for (String dir : stack) { |
| 24 | + result = "/" + dir + result; |
| 25 | + } |
| 26 | + return result.isEmpty() ? "/" : result; |
35 | 27 | }
|
36 |
| - } |
37 |
| - String result = ""; |
38 |
| - for (String dir : stack) { |
39 |
| - result = "/" + dir + result; |
40 |
| - } |
41 |
| - return result.isEmpty() ? "/" : result; |
42 | 28 | }
|
43 |
| - } |
44 | 29 | }
|
0 commit comments