728x90
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.
Constraints:
- 1 <= path.length <= 3000
- path consists of English letters, digits, period '.', slash '/' or '_'.
- path is a valid absolute Unix path.
Code:
var simplifyPath = function(path) {
// 경로를 슬래시를 기준으로 나눕니다.
const parts = path.split('/');
const stack = [];
// 각 부분에 대해 처리합니다.
for (let part of parts) {
// 비어있거나 현재 디렉터리를 나타내는 경우 무시합니다.
if (part === '' || part === '.') {
continue;
}
// 이전 디렉터리를 나타내는 경우 스택에서 pop합니다.
else if (part === '..') {
stack.pop();
}
// 그 외의 경우 스택에 추가합니다.
else {
stack.push(part);
}
}
// 간소화된 경로를 구성합니다.
const result = '/' + stack.join('/');
return result;
};
Solution Code:
var simplifyPath = function (path) {
// 간소화된 경로를 저장할 배열
const simplifiedPath = [];
// 경로를 디렉토리 단위로 나눔
const dirs = path.split("/");
// 모든 디렉토리에 대해 반복
for (const dir of dirs) {
// 빈 디렉토리나 현재 디렉토리인 경우 건너뜀
if (dir === "" || dir === ".") continue;
// 상위 디렉토리인 경우 이전 디렉토리를 제거
dir === ".." ? simplifiedPath.pop() : simplifiedPath.push(dir);
}
// '/'를 포함하여 간소화된 경로 반환
return "/" + simplifiedPath.join("/");
};
출처 : https://leetcode.com/problemset/all/
728x90
'LeetCode' 카테고리의 다른 글
[LeetCode] 73. Set Matrix Zeroes (0) | 2024.03.13 |
---|---|
[LeetCode] 72. Edit Distance (0) | 2024.03.01 |
[LeetCode] 70. Climbing Stairs (0) | 2024.02.23 |
[LeetCode] 69. Sqrt(x) (0) | 2024.02.23 |
[LeetCode] 68. Text Justification (0) | 2024.02.19 |