71. Simplify Path
June 24, 2025
04:32 AM
No headings found
Loading content...
No headings found
Problem
Bạn cần xử lý một chuỗi đường dẫn tuyệt đối kiểu Unix và trả về đường dẫn đã được rút gọn theo quy tắc sau:
Approach
Time and space complexity
Solution
1function simplifyPath(path: string): string {
2 const stack: string[] = [];
3 for (const segment of path.split('/')) {
4 if (segment === '' || segment === '.') continue;
5 if (segment === '..') {
6 if (stack.length) stack.pop()
7 } else {
8 stack.push(segment)
9 }
10 }
11
12 return '/' + stack.join('/')
13};