Simplify Path

Question

Given an absolute path for a file (Unix-style), simplify it.

Example `"/home/", => "/home"``

`"/a/./b/../../c/", => "/c"``

Challenge Did you consider the case where path = "/../"?

In this case, you should return "/".

Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".

In this case, you should ignore redundant slashes and return "/home/foo".

Thoughts

stack

reference reference

Solution

class Solution:
    # @param {string} path the original path
    # @return {string} the simplified path
    def simplifyPath(self, path):
        # Write your code here
        stack = []
        i =  0
        result = ""
        while i < len(path):
            #i == 0, it's "/"
            end = i + 1
            while end < len(path) and path[end] != "/":
                end += 1
            sub = path[i+1:end]
            if len(sub) > 0:
                if sub == "..":
                    if stack:
                        stack.pop()
                elif sub != ".":
                    stack.append(sub)
            i = end
        if not stack:
            return "/"
        for i in stack:
            result += "/" + i

        return result