Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def simplifyPath(self, path: str) -> str:
"""
Simplifies a Unix-style absolute path to its canonical form.

Args:
path: An absolute path string starting with '/'

Returns:
The simplified canonical path
"""
# Stack to keep track of valid directory names
stack = []

# Split the path by '/' and process each component
components = path.split('/')

for component in components:
# Skip empty strings (from consecutive slashes) and current directory markers
if component == '' or component == '.':
continue
# Parent directory - pop from stack if possible
elif component == '..':
if stack:
stack.pop()
# Valid directory or file name
else:
stack.append(component)

# Build the canonical path
# Start with '/' and join all directories with '/'
return '/' + '/'.join(stack)
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
function simplifyPath(path: string): string {
// Stack to keep track of valid directory names
const stack: string[] = [];

// Split the path by '/' and process each component
const components = path.split('/');

for (const component of components) {
// Skip empty strings (from consecutive slashes) and current directory markers
if (component === '' || component === '.') {
continue;
}
// Parent directory - pop from stack if possible
else if (component === '..') {
if (stack.length > 0) {
stack.pop();
}
}
// Valid directory or file name
else {
stack.push(component);
}
}

// Build the canonical path
// Start with '/' and join all directories with '/'
return '/' + stack.join('/');
}
Loading