This is essentially a interpreter for traversal commands


  • 0
    L

    Semantics of commands:
    . -- nop
    .. -- return to upper level
    dirs -- enter new directory
    \epsilon -- nop

    Now we can write the interpreter

    class Solution(object):
        def simplifyPath(self, path):
            """
            :type path: str
            :rtype: str
            """
            traversal_commands = path.split('/')[1:]
            state = []
            for command in traversal_commands:
                if command == '.' or command == '':
                    continue
                if command == '..':
                    state = state[:-1]
                else:  # dir -- needs lexical checks though
                    state.append(command)
    
            return '/' + '/'.join(state)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.