【leetcode】Simplify Path

题目简述:

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.

解题思路:

很明显是压栈弹栈的过程,难点在特殊情况要考虑周全,corner cases基本提示全了

class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        s = path.strip().split('/')
        sta = []
        for i in s:
            if i == '..':
                if len(sta) > 0:
                    sta.pop()
                else:
                    pass
            elif i == '.':
                pass
            elif i == '':
                pass
            else:
                sta.append(i)
        return '/'+'/'.join(sta)

s = Solution()
print s.simplifyPath("//home/")
print s.simplifyPath("/a/./b/../../c/")
print s.simplifyPath("/home/../../..")

你可能感兴趣的:(LeetCode)