Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.
The canonical path should have the following format:
Return the simplified canonical path.
Example 1:
Input: path = "/home/" Output: "/home" Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../" Output: "/" Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/" Output: "/home/foo" Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: path = "/a/./b/../../c/" Output: "/c"
Constraints:
풀이코드
import java.util.*;
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
String[] list = path.split("/");
ArrayList<String> arr = new ArrayList<>(Arrays.asList(list));
String answer = "";
for (String str : arr) {
if (str.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!str.isEmpty() && !str.equals(".")){
stack.push("/" + str);
}
System.out.println(stack);
}
ArrayList<String> result = new ArrayList<>(stack);
for (String rst : result) {
answer += rst;
}
return answer.equals("") ? "/" : answer;
}
}
풀이방식
path를 주어진 조건에 맞춰 축약하는 문제이다. 조건들에 맞춰서 경로를 계산하고 현재경로를 return 해주면된다.
[LeetCode] 1700. Number of Students Unable to Eat Lunch (0) | 2021.11.07 |
---|---|
[LeetCode] 20. Valid Parentheses (0) | 2021.11.07 |
[LeetCode] Running Sum of 1d Array (0) | 2021.05.01 |
[LeetCode] Two Sum (0) | 2021.04.27 |