Simplify Path

题目描述

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

For example,

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:**

  • "/../" => "/"
  • "/home//foo/" => "/home/foo"

解题方法

非stack方法

将string根据"/" split, 用一个string来记录path

  • 遇到.., 就将上一个dir去掉
  • 遇到.或者`, 表示//`这种情况,不做任何事

注意点

  • /路径的判断!

stack做法

/之间的都push到stack上,注意empty string不要push,

  • 遇到"..", 就pop
  • 遇到".", 什么都不做
  • 遇到others, push到stack上

Solution

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        if not path:
            return ""
        path = path.split("/")
        cur = "/"

        for p in path:
            if p == "..":
                if cur != "/":
                    cur = cur.split("/")[:-1]
                    cur = "/".join(cur)
                    if cur == "":
                        # e.g. "/a" would become ""
                        cur = "/"
            elif p != "." and p != "":
                # take care of ”/"
                if cur == "/":
                    cur += p
                else:
                    cur += "/" + p

        return cur

Reference