leetcode-study

71. Simplify Path

class Solution:
    def simplifyPath(self, path: str) -> str:
        """
        Simplify an absolute Unix-style file path.
        
        Parameters:
            path (str): A valid absolute Unix file path which may contain redundant slashes,
                        '.' (current directory) or '..' (parent directory).
        
        Returns:
            str: The simplified canonical path adhering to Unix-style rules.
        """
        stack = []  # Stack to keep track of the valid directory names in the path.
        
        # Split the path by '/' to handle each directory or file component.
        components = path.split('/')
        
        for component in components:
            # Skip empty components and '.' which signifies the current directory.
            if component == '' or component == '.':
                continue
            # For '..', pop the last valid directory if there is one (if not, we're at root).
            elif component == '..':
                if stack:
                    stack.pop()
            # Push valid directory or file names onto the stack.
            else:
                stack.append(component)
        
        # Rebuild the simplified path by joining the stack with '/' and prefixing with a slash.
        return '/' + '/'.join(stack)

Summary of Techniques and Approaches:

These techniques can be applied broadly to file system path simplification, expression evaluation, or any scenario where hierarchical and sequential data processing is required.