My reducer solution (using reduce function)


  • 0
    D

    Since we create a list by splitting the path into components anyway, then I've decided to use a reduce function, because we want to reduce the whole array to one value => shortened path.
    Looks pretty good to me :P

    class Solution(object):
        def simplifyPath(self, path):
            def reducer(acc, token):
                if token == "." or len(token) == 0: return acc
                elif token == "..":
                    if acc: acc.pop()
                    return acc
                else:
                    return acc + [token]
        
            tokens = path.split("/")
            result = reduce(reducer, tokens, [])
            return "/" + "/".join(result)

Log in to reply
 

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