https://leetcode-cn.com/problems/simplify-path/

# -*- coding:utf-8 -*-

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        command = path.split('/')
        stack = []
        for each in command:
            if '.' == each:
                continue
            elif '..' == each:
                if len(stack) > 0:
                    stack.pop()
            elif '' == each:
                continue
            else:
                stack.append(each)
        res = ''
        if len(stack) == 0:
            return '/'
        for each in stack:
            res += str('/' + each)
        return res
if __name__ == '__main__':
    path = "/a/./b/../../c/"
    path = "/a//b////c/d//././/.."
    path = '/../'
    path = '/home/'
    print(Solution().simplifyPath(path))

思路:使用/来分割path路径,然后根据不同的命令进行出入栈操作,如果遇到.和空,则不做操作,如果遇到..切栈不空则出栈,遇到其他的就说明是路径,入栈,然后在输出的时候将栈转换成路径字符串即可,同时需要注意栈空的特殊情况。

分类: 算法

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注