주어진 경로를 정리하는 문제이다.
특이점은 ‘.’과 ‘..’의 처리이다. 주어진 경로를 ‘/’를 기준으로 나누고 Deque를 사용해서 처리하면 될 것이다.
- 문자열을 ‘/’로 분할한다.
- Deque에 문자를 넣는다.
- 이때 처리할 문자가 ‘..’이라면 Deque이 비어있지 않다면 한 번 pop을 한다.
- 문자가 ‘.’ 이라면 별도 처리를 하지 않는다.
- 모든 작업이 끝난 뒤 ‘/’를 넣어가며 Deque의 문자들을 앞에서부터 꺼내 완성한다.
class Solution {
static final String PARENT = "..";
static final String CURRENT = ".";
static final String DELIMITER = "/";
public String simplifyPath(String path) {
Deque<String> stack = new ArrayDeque<>();
for (String s : path.split("/")) {
if (s.isEmpty()) continue;
if (s.equals(PARENT)) {
if (!stack.isEmpty()) {
stack.pollLast();
}
} else if (s.equals(CURRENT)) {
continue;
} else {
stack.addLast(s);
}
}
StringBuilder sb = new StringBuilder();
sb.append(DELIMITER);
while (!stack.isEmpty()) {
String s = stack.pollFirst();
sb.append(s).append(DELIMITER);
}
if (sb.length() != 1) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 11053 - 가장 긴 증가하는 부분 수열 (0) | 2024.10.18 |
---|---|
LeetCode 205 - Isomorphic Strings (0) | 2024.10.18 |
LeetCode 120 - Triangle (0) | 2024.10.18 |
LeetCode 54 - Spiral Matrix (0) | 2024.10.17 |
LeetCode 108 - Convert Sorted Array to Binary Search Tree (0) | 2024.10.17 |