【LeetCode】71. Simplify Path 解題報告(Python)

【LeetCode】71. Simplify Path 解題報告(Python)

標籤(空格分隔): LeetCodepython

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.me/linux


題目地址:https://leetcode.com/problems/simplify-path/description/app

題目描述:

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

For example,this

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

Corner Cases:spa

  • Did you consider the case where path = 「/../」?
    In this case, you should return 「/」.code

  • 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」.ip

題目大意

簡化linux路徑。leetcode

解題方法

看到這種來來回回,增增刪刪的題,通常都想到用棧。字符串

咱們把字符串按照/分割以後就獲得了每一個文件的目錄,而後判斷路徑是添加仍是向上層進行返回。這個題很簡單了。

有一個地方犯了小錯誤,不能寫成if dir == ‘..’ and stack: stack.pop()。這樣的話若是棧是空的,就把..進棧了。

class Solution(object):
    def simplifyPath(self, path):
        """ :type path: str :rtype: str """
        stack = list()
        dirs = path.split('/')
        for dir in dirs:
            if not dir or dir == '.':
                continue
            if dir == '..':
                if stack:
                    stack.pop()
            else:                
                stack.append(dir)
        return '/' + '/'.join(stack)

日期

2018 年 6 月 26 日 ———— 早睡早起

相關文章
相關標籤/搜索