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:
- The path starts with a single slash '/'.
- Any two directories are separated by a single slash '/'.
- The path does not end with a trailing '/'.
- The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
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:
- 1 <= path.length <= 3000
- path consists of English letters, digits, period '.', slash '/' or '_'.
- path is a valid absolute Unix path.
풀이코드
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 해주면된다.
- 매개변수로 받은 path를 split을 활용하여 '/'로 자르고 배열에 담는다
- 배열에 담은 값을 다시 ArrayList에 담아준다.
- list를 돌면서 해당 경로들을 stack에 담아준다.
- ..는 상위 디렉토리로 가는것이기때문에 stack에 최상단에 담은값을 지워주면 이전 디렉토리로 갈수있다.
- .은 현재 디렉토리 이므로, 들어온 경로를 /를 붙여서 그대로 stack에 담는다.
- 그렇게 담은 경로 stack을 list에 담고 list를 반복문을 통해 answer에 넣어주고 return해주면 풀이는 종료된다.
- 이때 stack을 list에 다시 담은 이유는 stack은 LIFO의 성질을 갖고있기때문에 순서를 다시 역순으로 돌려주기 위함
'알고리즘 > LeetCode' 카테고리의 다른 글
[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 |