Simple and clear python solution


  • 1
    Q
    class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        ans = []
        dirpath = filter(None,path.split('/'))
        for i in dirpath:
            if i == '.':
                continue
            elif i == '..':
                if ans:# avoid pop from empty dir, we know that parent path of '/' is '/' so we can safely ignore all the '..'
                    ans.pop()
            else:
                ans.append(i)
        return '/' + '/'.join(ans)

  • 0
    P

    same as your solution!


  • 0
    C

    Similar approach but shorter (use list comprehension to create s and deal with both "" and "." ). :

    def simplifyPath(self, path):
        s = [i for i in path.split("/") if i and i!="."]
        ans = []
        for n in s:
            if n!="..":
                ans.append(s)
            elif ans:
                ans.pop()
        return "/" + "/".join(ans)

Log in to reply
 

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