Simple Python AC code


  • 4
    A
    class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        result = []
        pathList = path.split('/')
        for content in pathList:
            if content:
                if content == '..':
                    try:
                        result.pop()
                    except:
                        result = []
                elif content != '.':
                    result.append(content)
        return '/'+'/'.join(result)

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    J

    nice use for try...except


  • 0
    C

    Do you need try block ?
    In the context of the problem if the result is empty while you are trying to pop() ie. you are going one level up at root dir level => your directory path need to have a ../ to simplify the final path relative to current dir.


  • 0
    G

    Try block seems unnecessary, here's a variation without it.

    class Solution(object):
        def simplifyPath(self, path):
            result = []
            pathList = path.split('/')
            for content in pathList:
                if content:
                    if content == '..':
                        if result:
                            result.pop()
                    elif content != '.':
                        result.append(content)
            return '/'+'/'.join(result)
    

Log in to reply
 

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